public static IWorkspace connectToSDE() { IPropertySet pPropSet = new PropertySetClass(); pPropSet.SetProperty("Server", "techserver"); pPropSet.SetProperty("Instance", "esri_sde"); pPropSet.SetProperty("user", "sdedata"); pPropSet.SetProperty("password", "sdedata"); pPropSet.SetProperty("version", "sde.DEFAULT"); IWorkspaceFactory pFact; IWorkspace pWorkspace; //IFeatureWorkspace pFeatureWorkspace; try { pFact = new SdeWorkspaceFactoryClass(); pWorkspace = pFact.Open(pPropSet, 0); //pFeatureWorkspace=pWorkspace as IFeatureWorkspace; //pFeatureWorkspace.CreateTable("CJTEST",pFieldsEdit as IFields,null,null,""); return pWorkspace; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } }
public static Blobber CreateBlobber() { BlobberRepository repository = new BlobberRepository(); repository.StartEdit(); Blobber b = repository.Create(); b.BlobberId = BLOBBER_ID; IFeatureLayer layer = new FeatureLayerClass(); layer.Name = BLOBBER_VALUE_1; IPropertySet properties = new PropertySetClass(); properties.SetProperty("VALUE1", BLOBBER_VALUE_1); properties.SetProperty("VALUE2", BLOBBER_VALUE_2); properties.SetProperty("VALUE3", BLOBBER_VALUE_3); b.Properties = properties; b.Store(); repository.StopEdit(true); return b; }
/// <summary>Apply the OSM Class Extension to the given table</summary> /// <remarks>Obtains an exclusive schema lock if possible otherwise throws an exception</remarks> public static void ApplyOSMClassExtension(this ITable table) { if ((table == null) || (table.Extension is IOSMClassExtension)) return; IClassSchemaEdit3 schemaEdit = table as IClassSchemaEdit3; if (schemaEdit == null) return; int osmIDIndex = table.Fields.FindField("OSMID"); using (SchemaLockManager lockMgr = new SchemaLockManager(table)) { UID osmClassExtensionUID = new UIDClass() { Value = _OSM_CLASS_EXT_GUID }; IPropertySet extensionPropertSet = null; if (osmIDIndex > -1) { // at release 2.1 we changed the OSMID field type to string, hence only when we find the string we are assuming version 2 if (table.Fields.get_Field(osmIDIndex).Type == esriFieldType.esriFieldTypeString) { extensionPropertSet = new PropertySetClass(); extensionPropertSet.SetProperty("VERSION", _OSM_EXTENSION_VERSION); } } schemaEdit.AlterClassExtensionCLSID(osmClassExtensionUID, extensionPropertSet); schemaEdit.AlterClassExtensionProperties(extensionPropertSet); } }
public object GetWorkspace(string strType, string strArgs) { IWorkspaceFactory wsf = null; IWorkspace m_SystemWorkspace = null; switch (strType) { case "PGDB": wsf = new AccessWorkspaceFactoryClass(); m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0); break; case "FILEGDB": wsf = new ShapefileWorkspaceFactoryClass(); m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0); break; case "SDE": IPropertySet pSet = new PropertySetClass(); string[] argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string strArg in argList) { string[] argPair = strArg.Split(new char[] { ':' }); pSet.SetProperty(argPair[0], argPair[1]); } wsf = new SdeWorkspaceFactoryClass(); m_SystemWorkspace = wsf.Open(pSet, 0); break; default: throw new Exception("系统Workspace配置了无法识别的数据库:Workspace类型应该在PGDB、FILEGDB和SDE之内"); } return m_SystemWorkspace; }
public static IWorkspace GetWorkspace(Hashtable pPropList, string progID) { try { IPropertySet2 propertySets = new PropertySetClass(); foreach (string paraName in pPropList.Keys) propertySets.SetProperty(paraName.ToUpper(), pPropList[paraName]); IWorkspaceFactory wsf = new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass(); return wsf.Open(propertySets, 0); return (new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass()).Open(propertySets, 0); IWorkspaceName2 workspaceName = new WorkspaceNameClass(); workspaceName.ConnectionProperties = propertySets; // 类型库需要动态设置 workspaceName.WorkspaceFactoryProgID = progID; IName pName = workspaceName as IName; IWorkspace workspace = pName.Open() as IWorkspace; //IWorkspace workspace = pName.Open() as IWorkspace; return workspace; } catch (Exception ex) { MessageBox.Show("SDE连接参数不正确,请和系统管理员联系!"); return null; } }
protected override void OnClick() { IMxDocument mxDoc = (IMxDocument)ArcMap.Application.Document; IWMSGroupLayer wmsMapLayer = new WMSMapLayerClass(); IWMSConnectionName connName = new WMSConnectionNameClass(); IPropertySet propSet = new PropertySetClass(); propSet.SetProperty("URL", "https://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer"); connName.ConnectionProperties = propSet; //Put the WMS service layers in a DataLayer IDataLayer dataLayer = (IDataLayer)wmsMapLayer; dataLayer.Connect((IName)connName); // Get access to WMS service and layer propeties IWMSServiceDescription serviceDesc = wmsMapLayer.WMSServiceDescription; IWMSLayerDescription groupDesc = serviceDesc.LayerDescription[0]; //Clear existing WMS service group layer. wmsMapLayer.Clear(); //Create an empty layer and populate it with the desired sub layer index. ILayer newLayer; IWMSLayer newWMSLayer = wmsMapLayer.CreateWMSLayer(groupDesc.LayerDescription[1]); newLayer = (ILayer)newWMSLayer; wmsMapLayer.InsertLayer(newLayer, 0); //Add the layer to the map. mxDoc.FocusMap.AddLayer((ILayer)wmsMapLayer); IActiveView activeView = (IActiveView)mxDoc.FocusMap; activeView.Refresh(); ArcMap.Application.CurrentTool = null; }
private void GeocodeAddress() { // Get the locator System.Object obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriLocation.LocatorManager")); ILocatorManager2 locatorManager = obj as ILocatorManager2; ILocatorWorkspace locatorWorkspace = locatorManager.GetLocatorWorkspaceFromPath(@"C:\California_fgdb.gdb"); ILocator locator = locatorWorkspace.GetLocator("California_city_state_zip_94_new"); // Set up the address properties IAddressInputs addressInputs = locator as IAddressInputs; IFields addressFields = addressInputs.AddressFields; IPropertySet addressProperties = new PropertySetClass(); addressProperties.SetProperty(addressFields.get_Field(0).Name, this.AddressTextBox.Text); addressProperties.SetProperty(addressFields.get_Field(1).Name, this.CityTextBox.Text); addressProperties.SetProperty(addressFields.get_Field(2).Name, this.StateTextBox.Text); addressProperties.SetProperty(addressFields.get_Field(3).Name, this.ZipTextBox.Text); // Match the Address IAddressGeocoding addressGeocoding = locator as IAddressGeocoding; IPropertySet resultSet = addressGeocoding.MatchAddress(addressProperties); // Print out the results object names, values; resultSet.GetAllProperties(out names, out values); string[] namesArray = names as string[]; object[] valuesArray = values as object[]; int length = namesArray.Length; IPoint point = null; for (int i = 0; i < length; i++) { if (namesArray[i] != "Shape") this.ResultsTextBox.Text += namesArray[i] + ": " + valuesArray[i].ToString() + "\n"; else { if (point != null && !point.IsEmpty) { point = valuesArray[i] as IPoint; this.ResultsTextBox.Text += "X: " + point.X + "\n"; this.ResultsTextBox.Text += "Y: " + point.Y + "\n"; } } } this.ResultsTextBox.Text += "\n"; }
public static void AddIdahoWms(string idahoId, string groupLayerName, string token) { IGroupLayer groupLayer = new GroupLayerClass(); groupLayer.Name = groupLayerName; var wmsMapLayer = new WMSMapLayerClass(); // create and configure wms connection name, this is used to store the connection properties IWMSConnectionName pConnName = new WMSConnectionNameClass(); IPropertySet propSet = new PropertySetClass(); // create the idaho wms url var idahoUrl = string.Format( "http://idaho.geobigdata.io/v1/wms/idaho-images/{0}/{1}/mapserv?", idahoId, token); // setup the arcmap connection properties propSet.SetProperty("URL", idahoUrl); pConnName.ConnectionProperties = propSet; //uses the name information to connect to the service IDataLayer dataLayer = wmsMapLayer; try { dataLayer.Connect((IName)pConnName); } catch (Exception e) { Jarvis.Logger.Error("Problems connecting to WMS: " + e.Message); } // get wms service description var serviceDesc = wmsMapLayer.IWMSGroupLayer_WMSServiceDescription; ILayer wmsLayer = null; // add layers for the wms currently there will only be one. for (var i = 0; i <= serviceDesc.LayerDescriptionCount - 1; i++) { var layerDesc = serviceDesc.LayerDescription[i]; var grpLayer = wmsMapLayer.CreateWMSGroupLayers(layerDesc); for (var j = 0; j <= grpLayer.Count - 1; j++) { wmsLayer = wmsMapLayer; wmsMapLayer.Name = idahoId; } } // turn on sub layers, add it to arcmap and move it to top of TOC // SublayerVisibleOn(wmsLayer); groupLayer.Add(wmsLayer); // turn on sub layers, add it to arcmap and move it to top of TOC ArcMap.Document.AddLayer(groupLayer); ArcMap.Document.FocusMap.MoveLayer(groupLayer, 0); }
public IFeatureLayer OracleQueryLayer() { // 创建SqlWorkspaceFactory的对象 Type pFactoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SqlWorkspaceFactory"); IWorkspaceFactory pWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(pFactoryType); // 构造连接数据库的参数 IPropertySet pConnectionProps = new PropertySetClass(); pConnectionProps.SetProperty("dbclient", "Oracle11g"); pConnectionProps.SetProperty("serverinstance", "esri"); pConnectionProps.SetProperty("authentication_mode", "DBMS"); pConnectionProps.SetProperty("user", "scott"); pConnectionProps.SetProperty("password", "arcgis"); // 打开工作空间 IWorkspace workspace = pWorkspaceFactory.Open(pConnectionProps, 0); ISqlWorkspace pSQLWorkspace = workspace as ISqlWorkspace; //获取数据库中的所有表的名称 //IStringArray pStringArray= pSQLWorkspace.GetTables(); //for (int i = 0; i < pStringArray.Count; i++) //{ // MessageBox.Show(pStringArray.get_Element(i)); //} // 构造过滤条件 SELECT * FROM PointQueryLayer IQueryDescription queryDescription = pSQLWorkspace.GetQueryDescription("SELECT * FROM TEST"); ITable pTable = pSQLWorkspace.OpenQueryClass("QueryLayerTest", queryDescription); IFeatureLayer pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pTable as IFeatureClass; return pFeatureLayer; }
/// <summary> /// 连接到WMS服务器,载入WMS图层 /// </summary> /// <param name="axMapControl1">axMapControl控件</param> /// <param name="url">WMS服务器地址</param> public static void Connect2WMS(AxMapControl axMapControl1, string url) { #region 初始化环境 IPropertySet pPropertyset = new PropertySetClass(); pPropertyset.SetProperty("url", url); IWMSConnectionName pWMSConnectionName = new WMSConnectionNameClass(); pWMSConnectionName.ConnectionProperties = pPropertyset; ILayerFactory pLayerFactory = new EngineWMSMapLayerFactoryClass();//Provides access to members that control the creation of layers through a factory. IWMSGroupLayer pWmsMapLayer = new WMSMapLayerClass(); IDataLayer pDataLayer = pWmsMapLayer as IDataLayer; pDataLayer.Connect(pWMSConnectionName as IName); IWMSServiceDescription pWmsServiceDesc = pWmsMapLayer.WMSServiceDescription; #endregion #region 获取WMS图层 for (int i = 0; i < pWmsServiceDesc.LayerDescriptionCount; i++) { IWMSLayerDescription pWmsLayerDesc = pWmsServiceDesc.get_LayerDescription(i); ILayer pNewLayer = null; if (pWmsLayerDesc.LayerDescriptionCount == 0) { IWMSLayer pWmsLayer = pWmsMapLayer.CreateWMSLayer(pWmsLayerDesc); pNewLayer = pWmsLayer as ILayer; } else { IWMSGroupLayer pWmsGroupLayer = pWmsMapLayer.CreateWMSGroupLayers(pWmsLayerDesc); for (int j = 0; j < pWmsGroupLayer.Count; j++) { ILayer layer = pWmsGroupLayer.get_Layer(j); if (layer.Name != "admin") { pWmsMapLayer.InsertLayer(layer, 0); layer.Visible = true; } } } } #endregion #region 收尾工作 ILayer pLayer = pWmsMapLayer as ILayer; pLayer.Name = pWmsServiceDesc.WMSTitle; pLayer.Visible = true; axMapControl1.AddLayer(pLayer, 0); IEnvelope pEnv = axMapControl1.FullExtent; pEnv.Expand(0.8, 0.8, true); axMapControl1.Extent = pEnv; #endregion }
public override void OnClick() { if (m_pAOIPanel.CurrentJob != null) { //show form AddressDialog pAddressDialog = new AddressDialog(); if (pAddressDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { ILocatorManager pLocatorMgr = new LocatorManagerClass(); ILocatorWorkspace pLocatorWS = pLocatorMgr.GetLocatorWorkspaceFromPath(m_strWorkspace); IAddressGeocoding pLocator = (IAddressGeocoding)pLocatorWS.GetLocator(m_strLocator); IPropertySet addressProperties = new PropertySetClass(); addressProperties.SetProperty("Street", pAddressDialog.street); IPropertySet matchProperties = pLocator.MatchAddress(addressProperties); if(pLocator.MatchFields.FieldCount == 0) { System.Windows.Forms.MessageBox.Show("No address found"); return; } IPoint pPoint = null; for(int i = 0; i < pLocator.MatchFields.FieldCount; i++) { if(pLocator.MatchFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry) { object pObject = matchProperties.GetProperty(pLocator.MatchFields.get_Field(i).Name); if(pObject is IPoint) pPoint = (IPoint) pObject; } } //calculate AOI ITopologicalOperator pTopo = (ITopologicalOperator)pPoint; IGeometry pGeom = pTopo.Buffer(100); IEnvelope pMyAOI = pGeom.Envelope; m_pAOIPanel.CurrentAOI = CreatePolyFromEnv(pMyAOI); IEnvelope pEnv = pGeom.Envelope; pEnv.Expand(2, 2, true); m_hookHelper.ActiveView.Extent = pEnv; m_hookHelper.ActiveView.Refresh(); } } }
public static int CreateAndGetOID() { BlobberRepository repository = new BlobberRepository(); repository.StartEdit(); Blobber b = repository.Create(); b.BlobberId = BLOBBER_ID; IPropertySet properties = new PropertySetClass(); properties.SetProperty("VALUE1", BLOBBER_VALUE_1); properties.SetProperty("VALUE2", BLOBBER_VALUE_2); properties.SetProperty("VALUE3", BLOBBER_VALUE_3); b.Properties = properties; b.Store(); repository.StopEdit(true); return b.ObjectId; }
//Create connection property set for Tracking Server private IPropertySet CreateTrackingServerConnectionProperties() { IPropertySet connectionProperties = new PropertySetClass(); connectionProperties.SetProperty("SERVERNAME", TS_SERVER_NAME); connectionProperties.SetProperty("AMS_CONNECTION_NAME", "Sample TS Connection"); //This is the standard AMS connection editor, this would only be different if you wrote your own connector connectionProperties.SetProperty("AMS_CONNECTOR_EDITOR", "{1C6BA545-2F59-11D5-B7E2-00010265ADC5}"); //This is the standard AMS connector, this would only be different if you wrote your own connector connectionProperties.SetProperty("AMS_CONNECTOR", "{F6FC70F5-5778-11D6-B841-00010265ADC5}"); connectionProperties.SetProperty("AMS_USER_NAME", ""); connectionProperties.SetProperty("TMS_USER_PWD", ""); return connectionProperties; }
public static IPropertySet PropertySetFromString(String propertySetText) { if (String.IsNullOrEmpty(propertySetText)) throw new ArgumentNullException("propertySetText"); IPropertySet propertySet = new PropertySetClass(); String[] properties = propertySetText.Split(new[] { ';' }); for (int i = 0; i < properties.Count(); i++) { if (String.IsNullOrEmpty(properties[i])) continue; String[] propertyParts = properties[i].Split(new[] { '=' }); // Remove [ ] String name = propertyParts[0].Substring(1, propertyParts[0].Length - 2); String value = propertyParts[1]; propertySet.SetProperty(name, value); } return propertySet; }
public static IWorkspace WorkgroupArcSdeWorkspaceFromPropertySet() { IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("SERVER", "172.25.3.110"); propertySet.SetProperty("INSTANCE", "sde:oracle11g:sigprod_oda"); propertySet.SetProperty("USER", "TLOB"); propertySet.SetProperty("PASSWORD", "TeleobservacionSGC"); propertySet.SetProperty("VERSION", "SDE.DEFAULT"); propertySet.SetProperty("AUTHENTICATION_MODE", "DBMS"); try { Type factoryType = Type.GetTypeFromProgID( "esriDataSourcesGDB.SdeWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); return workspaceFactory.Open(propertySet, 0); } catch (Exception ex) { MessageBox.Show("Error conectandose a la base de datos" + ex.Message); return null; } }
private void listProjects_SelectedIndexChanged(object sender, EventArgs e) { // Need to clear the versions when selected this.listVersions.DataSource = null; string selectedProject = null; try { selectedProject = (string)this.listProjects.SelectedValue; } catch { return; } if (selectedProject == null) { return; } // Prompt the user to select a version. Open the database IPropertySet connectionProperties = new PropertySetClass(); connectionProperties.SetProperty("SERVER", "malachite\\azgsgeodatabases"); connectionProperties.SetProperty("INSTANCE", "sde:sqlserver:malachite\\azgsgeodatabases"); connectionProperties.SetProperty("DATABASE", selectedProject); connectionProperties.SetProperty("AUTHENTICATION_MODE", "OSA"); connectionProperties.SetProperty("VERSION", "dbo.Default"); IWorkspaceFactory wsFact = new SdeWorkspaceFactoryClass(); IVersionedWorkspace vWs = (IVersionedWorkspace)wsFact.Open(connectionProperties, 0); // Build a DataTable to bind to the listbox control DataTable verTable = new DataTable(); DataColumn verName = new DataColumn(); verName.ColumnName = "VersionName"; verName.DataType = typeof(string); verTable.Columns.Add(verName); IEnumVersionInfo theseVersions = vWs.Versions; IVersionInfo aVersion = theseVersions.Next(); while (aVersion != null) { string thisVersionName = (string)aVersion.VersionName; string[] Split = thisVersionName.Split(new char[] { '.' }); verTable.Rows.Add(Split[1]); aVersion = theseVersions.Next(); } this.listVersions.DataSource = verTable; this.listVersions.DisplayMember = "VersionName"; this.listVersions.ValueMember = "VersionName"; }
private void AddAGSService(string fileName) { try { IMxDocument mxDoc = (IMxDocument)m_application.Document; IMap map = (IMap)mxDoc.FocusMap; IActiveView activeView = (IActiveView)map; bool isAlreadyInMap = false; if (isAlreadyInMap) { ShowErrorMessageBox(StringResources.MapServiceLayerAlreadyExistInMap); return; } else { if (fileName.ToLower().Contains("http") && !fileName.ToLower().Contains("arcgis/rest")) { if(fileName.EndsWith("MapServer")) fileName = fileName.Remove(fileName.LastIndexOf("MapServer")); String[] s = fileName.ToLower().Split(new String[]{"/services"}, StringSplitOptions.RemoveEmptyEntries); IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("URL", s[0] + "/services"); // fileName IMapServer mapServer = null; IAGSServerConnectionFactory pAGSServerConFactory = new AGSServerConnectionFactory(); IAGSServerConnection agsCon = pAGSServerConFactory.Open(propertySet,0); IAGSEnumServerObjectName pAGSSObjs = agsCon.ServerObjectNames; IAGSServerObjectName pAGSSObj = pAGSSObjs.Next(); while (pAGSSObj != null) { if(pAGSSObj.Type=="MapServer" && pAGSSObj.Name.ToLower() == s[1].TrimStart('/').TrimEnd('/')){ break; } pAGSSObj = pAGSSObjs.Next(); } IName pName = (IName) pAGSSObj; IAGSServerObject pAGSO = (IAGSServerObject) pName.Open(); mapServer = (IMapServer) pAGSO; IPropertySet prop = new PropertySetClass(); prop.SetProperty("URL", fileName); prop.SetProperty("Name",pAGSSObj.Name); IMapServerLayer layer = new MapServerLayerClass(); layer.ServerConnect(pAGSSObj,mapServer.get_MapName(0)); mxDoc.AddLayer((ILayer)layer); } else { IGxFile pGxFile; if (fileName.ToLower().EndsWith(".tif")) { IRasterLayer pGxLayer = (IRasterLayer)new RasterLayer(); pGxLayer.CreateFromFilePath(fileName); if (pGxLayer.Valid) { map.AddLayer((ILayer)pGxLayer); } } else { if (fileName.ToLower().Contains("http") && fileName.ToLower().Contains("arcgis/rest")) { String[] s = fileName.ToLower().Split(new String[] { "/rest" }, StringSplitOptions.RemoveEmptyEntries); IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("URL", s[0] + "/services"); // fileName IMapServer mapServer = null; IAGSServerConnectionFactory pAGSServerConFactory = new AGSServerConnectionFactory(); IAGSServerConnection agsCon = pAGSServerConFactory.Open(propertySet, 0); IAGSEnumServerObjectName pAGSSObjs = agsCon.ServerObjectNames; IAGSServerObjectName pAGSSObj = pAGSSObjs.Next(); String[] parts = s[1].ToLower().Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries); while (pAGSSObj != null) { if (pAGSSObj.Type == "MapServer" && pAGSSObj.Name.ToLower() == parts[1]) { break; } pAGSSObj = pAGSSObjs.Next(); } IName pName = (IName)pAGSSObj; IAGSServerObject pAGSO = (IAGSServerObject)pName.Open(); mapServer = (IMapServer)pAGSO; IPropertySet prop = new PropertySetClass(); prop.SetProperty("URL", fileName); prop.SetProperty("Name", pAGSSObj.Name); IMapServerLayer layer = new MapServerLayerClass(); layer.ServerConnect(pAGSSObj, mapServer.get_MapName(0)); mxDoc.AddLayer((ILayer)layer); } else { IGxLayer pGxLayer = new GxLayer(); pGxFile = (GxFile)pGxLayer; pGxFile.Path = fileName; if (pGxLayer.Layer != null) { map.AddLayer(pGxLayer.Layer); } } } } } } catch (Exception ex) { ShowErrorMessageBox(StringResources.AddArcGISLayerFailed + "\r\n" + ex.Message); } }
/// <summary> /// create image service configuration /// </summary> private static void CreateISConfig() { try { if (!ConnectAGS(restAdmin)) return; //get source type esriImageServiceSourceType sourceType = GetSourceType(sourcePath); //connect to ArcGIS Server and create configuration IServerObjectConfiguration5 soConfig = (IServerObjectConfiguration5)soAdmin.CreateConfiguration(); //set general service parameters soConfig.Name = serviceName; soConfig.TypeName = "ImageServer"; soConfig.TargetCluster = "default"; soConfig.StartupType = esriStartupType.esriSTAutomatic; soConfig.IsPooled = true; soConfig.IsolationLevel = esriServerIsolationLevel.esriServerIsolationHigh; soConfig.MinInstances = 1; soConfig.MaxInstances = 2; //customize recycle properties IPropertySet propertySet_Recycle = soConfig.RecycleProperties; propertySet_Recycle.SetProperty("Interval", "24"); //path to the data IPropertySet propertySet = soConfig.Properties; IWorkspace workspace = ((IDataset)rasterDataset).Workspace; if (workspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace) { IWorkspaceName2 wsName2 = ((IDataset)workspace).FullName as IWorkspaceName2; string connString = wsName2.ConnectionString; propertySet.SetProperty("ConnectionString", connString); propertySet.SetProperty("Raster", ((IDataset)rasterDataset).Name); } else propertySet.SetProperty("Path", sourcePath); propertySet.SetProperty("EsriImageServiceSourceType", sourceType.ToString()); //MIME+URL (virtual directory) propertySet.SetProperty("SupportedImageReturnTypes", "MIME+URL"); IEnumServerDirectory dirs = soAdmin.GetServerDirectories(); dirs.Reset(); IServerDirectory serverDir = dirs.Next(); while (serverDir != null) { if (((IServerDirectory2)serverDir).Type == esriServerDirectoryType.esriSDTypeOutput) { propertySet.SetProperty("OutputDir", serverDir.Path); propertySet.SetProperty("VirtualOutputDir", serverDir.URL); break; } serverDir = dirs.Next(); } //copy right propertySet.SetProperty("CopyRight", ""); //properties for a mosaic dataset; if (sourceType == esriImageServiceSourceType.esriImageServiceSourceTypeMosaicDataset) { IFunctionRasterDataset functionRasterDataset = (IFunctionRasterDataset)rasterDataset; IPropertySet propDefaults = functionRasterDataset.Properties; object names, values; propDefaults.GetAllProperties(out names, out values); List<string> propNames = new List<string>(); propNames.AddRange((string[])names); if (propNames.Contains("MaxImageHeight")) propertySet.SetProperty("MaxImageHeight", propDefaults.GetProperty("MaxImageHeight"));//4100 if (propNames.Contains("MaxImageWidth")) propertySet.SetProperty("MaxImageWidth", propDefaults.GetProperty("MaxImageWidth"));//15000 if (propNames.Contains("AllowedCompressions")) propertySet.SetProperty("AllowedCompressions", propDefaults.GetProperty("AllowedCompressions"));//"None,JPEG,LZ77,LERC" if (propNames.Contains("DefaultResamplingMethod")) propertySet.SetProperty("DefaultResamplingMethod", propDefaults.GetProperty("DefaultResamplingMethod"));//0 if (propNames.Contains("DefaultCompressionQuality")) propertySet.SetProperty("DefaultCompressionQuality", propDefaults.GetProperty("DefaultCompressionQuality"));//75 if (propNames.Contains("MaxRecordCount")) propertySet.SetProperty("MaxRecordCount", propDefaults.GetProperty("MaxRecordCount"));//500 if (propNames.Contains("MaxMosaicImageCount")) propertySet.SetProperty("MaxMosaicImageCount", propDefaults.GetProperty("MaxMosaicImageCount"));//20 if (propNames.Contains("MaxDownloadSizeLimit")) propertySet.SetProperty("MaxDownloadSizeLimit", propDefaults.GetProperty("MaxDownloadSizeLimit"));//20 if (propNames.Contains("MaxDownloadImageCount")) propertySet.SetProperty("MaxDownloadImageCount", propDefaults.GetProperty("MaxDownloadImageCount"));//20 if (propNames.Contains("AllowedFields")) propertySet.SetProperty("AllowedFields", propDefaults.GetProperty("AllowedFields"));//"Name,MinPS,MaxPS,LowPS,HighPS,CenterX,CenterY" if (propNames.Contains("AllowedMosaicMethods")) propertySet.SetProperty("AllowedMosaicMethods", propDefaults.GetProperty("AllowedMosaicMethods"));//"Center,NorthWest,LockRaster,ByAttribute,Nadir,Viewpoint,Seamline" if (propNames.Contains("AllowedItemMetadata")) propertySet.SetProperty("AllowedItemMetadata", propDefaults.GetProperty("AllowedItemMetadata"));//"Full" if (propNames.Contains("AllowedMensurationCapabilities")) propertySet.SetProperty("AllowedMensurationCapabilities", propDefaults.GetProperty("AllowedMensurationCapabilities"));//"Full" if (propNames.Contains("DefaultCompressionTolerance")) propertySet.SetProperty("DefaultCompressionTolerance", propDefaults.GetProperty("DefaultCompressionTolerance"));//"0.01" LERC compression //propertySet.SetProperty("RasterFunctions", @"\\server\dir\rft1.rft.xml,\\server\dir\rft2.rft.xml");//"put raster function templates here, the first one is applied to exportimage request by default" //propertySet.SetProperty("RasterTypes", @"Raster Dataset,\\server\dir\art1.art.xml,\\server\dir\art2.art");//"put raster types here" //propertySet.SetProperty("DynamicImageWorkspace", @"\\server\dynamicImageDir"); //put the workspace that holds uploaded imagery here //propertySet.SetProperty("supportsOwnershipBasedAccessControl", true); //ownership based access control //propertySet.SetProperty("AllowOthersToUpdate", true); //allow others to update a catalog item //propertySet.SetProperty("AllowOthersToDelete", true); //allow others to delete a catalog item //propertySet.SetProperty("DownloadDir", ""); //put the download directory here //propertySet.SetProperty("VirutalDownloadDir", ""); //put the virtual download directory here } else { propertySet.SetProperty("MaxImageHeight", 4100); propertySet.SetProperty("MaxImageWidth", 15000); propertySet.SetProperty("AllowedCompressions", "None,JPEG,LZ77"); propertySet.SetProperty("DefaultResamplingMethod", 0); propertySet.SetProperty("DefaultCompressionQuality", 75);//for jpg compression propertySet.SetProperty("DefaultCompressionTolerance", 0.01);//for LERC compression // rasterDataset = OpenRasterDataset(sourcePath); IMensuration measure = new MensurationClass(); measure.Raster = ((IRasterDataset2)rasterDataset).CreateFullRaster(); string mensurationCaps = ""; if (measure.CanMeasure) mensurationCaps = "Basic"; if (measure.CanMeasureHeightBaseToTop) mensurationCaps += ",Base-Top Height"; if (measure.CanMeasureHeightBaseToTopShadow) mensurationCaps += ",Base-Top Shadow Height"; if (measure.CanMeasureHeightTopToTopShadow) mensurationCaps += ",Top-Top Shadow Height"; propertySet.SetProperty("AllowedMensurationCapabilities", mensurationCaps); //set mensuration here } //not cached propertySet.SetProperty("IsCached", false); propertySet.SetProperty("IgnoreCache", true); propertySet.SetProperty("UseLocalCacheDir", false); propertySet.SetProperty("ClientCachingAllowed", false); //propertySet.SetProperty("DEM", ""); //put the elevation raster dataset or service for 3D mensuration, may need to add 3D to AllowedMensurationCapabilities //convert colormap to RGB or not propertySet.SetProperty("ColormapToRGB", false); //whether to return jpgs for all jpgpng request or not propertySet.SetProperty("ReturnJPGPNGAsJPG", false); //allow server to process client defined function propertySet.SetProperty("AllowFunction", true); //allow raster function //capabilities if (sourceType == esriImageServiceSourceType.esriImageServiceSourceTypeMosaicDataset) soConfig.Info.SetProperty("Capabilities", "Image,Catalog,Metadata,Mensuration"); //Full set: Image,Catalog,Metadata,Download,Pixels,Edit,Mensuration else soConfig.Info.SetProperty("Capabilities", "Image,Metadata,Mensuration"); //enable wcs, assume data has spatial reference soConfig.set_ExtensionEnabled("WCSServer", true); IPropertySet wcsInfo = new PropertySetClass(); wcsInfo.SetProperty("WebEnabled", "true"); soConfig.set_ExtensionInfo("WCSServer", wcsInfo); IPropertySet propertySetWCS = new PropertySetClass(); propertySetWCS.SetProperty("CustomGetCapabilities", false); propertySetWCS.SetProperty("PathToCustomGetCapabilitiesFiles", ""); soConfig.set_ExtensionProperties("WCSServer", propertySetWCS); //enable wms soConfig.set_ExtensionEnabled("WMSServer", true); IPropertySet wmsInfo = new PropertySetClass(); wmsInfo.SetProperty("WebEnabled", "true"); soConfig.set_ExtensionInfo("WMSServer", wmsInfo); IPropertySet propertySetWMS = new PropertySetClass(); propertySetWMS.SetProperty("name", "WMS"); //set other properties here soConfig.set_ExtensionProperties("WMSServer", propertySetWMS); //add configuration and start soAdmin.AddConfiguration(soConfig); soAdmin.StartConfiguration(serviceName, "ImageServer"); if (soAdmin.GetConfigurationStatus(serviceName, "ImageServer").Status == esriConfigurationStatus.esriCSStarted) Console.WriteLine("{0} on {1} has been configured and started.", serviceName, restAdmin); else Console.WriteLine("{0} on {1} was configured but can not be started, please investigate.", serviceName, restAdmin); if (rasterDataset != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterDataset); } catch (Exception exc) { Console.WriteLine("Error: {0}", exc.Message); } }
// // // public static IFeatureWorkspace openPDB(string filePath) { try { IWorkspaceFactory pWSF = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pFWS; IPropertySet pPropset = new PropertySetClass(); pPropset.SetProperty("DATABASE", filePath); pFWS = pWSF.Open(pPropset, 0) as IFeatureWorkspace; return pFWS; } catch (Exception e) { MessageBox.Show(e.Message); return null; } }
public static void TestThumbnailBuilder(string rasterTypeName, string rasterTypeProductFilter, string rasterTypeProductName, string dataSource, string dataSourceFilter, string fgdbParentFolder, bool saveToArt, string customTypeFilePath, bool clearGdbDirectory) { try { string[] rasterProductNames = rasterTypeProductName.Split(';'); string nameString = rasterTypeName.Replace(" ", "") + rasterTypeProductFilter.Replace(" ", "") + rasterProductNames[0].Replace(" ", ""); #region Directory Declarations string fgdbName = nameString + ".gdb"; string fgdbDir = fgdbParentFolder + "\\" + fgdbName; string MosaicDatasetName = nameString + "MD"; #endregion #region Global Declarations IMosaicDataset theMosaicDataset = null; IMosaicDatasetOperation theMosaicDatasetOperation = null; IMosaicWorkspaceExtensionHelper mosaicExtHelper = null; IMosaicWorkspaceExtension mosaicExt = null; #endregion #region Create File GDB Console.WriteLine("Creating File GDB: " + fgdbName); if (clearGdbDirectory) { try { Console.WriteLine("Emptying Gdb folder."); System.IO.Directory.Delete(fgdbParentFolder, true); System.IO.Directory.CreateDirectory(fgdbParentFolder); } catch (System.IO.IOException EX) { Console.WriteLine(EX.Message); return; } } // Create a File Gdb Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory FgdbFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); FgdbFactory.Create(fgdbParentFolder, fgdbName, null, 0); #endregion #region Create Mosaic Dataset try { Console.WriteLine("Create Mosaic Dataset: " + MosaicDatasetName); // Setup workspaces. IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace fgdbWorkspace = workspaceFactory.OpenFromFile(fgdbDir, 0); // Create Srs ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference mosaicSrs = spatialrefFactory.CreateProjectedCoordinateSystem( (int)(esriSRProjCSType.esriSRProjCS_World_Mercator)); // Create the mosaic dataset creation parameters object. ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass(); // Create the mosaic workspace extension helper class. mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass(); // Find the right extension from the workspace. mosaicExt = mosaicExtHelper.FindExtension(fgdbWorkspace); // Use the extension to create a new mosaic dataset, supplying the // spatial reference and the creation parameters object created above. theMosaicDataset = mosaicExt.CreateMosaicDataset(MosaicDatasetName, mosaicSrs, creationPars, ""); theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset); } catch (Exception exc) { Console.WriteLine("Error: Failed to create Mosaic Dataset : {0}.", MosaicDatasetName + " " + exc.Message); return; } #endregion #region Create Custom Raster Type Console.WriteLine("Preparing Raster Type"); // Create a Raster Type Name object. IRasterTypeName theRasterTypeName = new RasterTypeNameClass(); // Assign the name of the Raster Type to the name object. // The Name field accepts a path to an .art file as well // the name for a built in Raster Type. theRasterTypeName.Name = rasterTypeName; // Use the Open function from the IName interface to get the Raster Type object. IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open()); if (theRasterType == null) { Console.WriteLine("Error:Raster Type not found " + rasterTypeName); return; } #endregion #region Prepare Raster Type // Set the URI Filter on the loaded raster type. if (rasterTypeProductFilter != "") { // Get the supported URI filters from the raster type object using the // raster type properties interface. IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters; IItemURIFilter productFilter = null; for (int i = 0; i < mySuppFilters.Count; ++i) { // Set the desired filter from the supported filters. productFilter = (IItemURIFilter)mySuppFilters.get_Element(i); if (productFilter.Name == rasterTypeProductFilter) { theRasterType.URIFilter = productFilter; } } } // Enable the correct templates in the raster type. bool enableTemplate = false; if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != "")) { // Get the supported item templates from the raster type. IItemTemplateArray templateArray = theRasterType.ItemTemplates; for (int i = 0; i < templateArray.Count; ++i) { // Go through the supported item templates and enable the ones needed. IItemTemplate template = templateArray.get_Element(i); enableTemplate = false; for (int j = 0; j < rasterProductNames.Length; ++j) { if (template.Name == rasterProductNames[j]) { enableTemplate = true; } } if (enableTemplate) { template.Enabled = true; } else { template.Enabled = false; } } } ((IRasterTypeProperties)theRasterType).DataSourceFilter = dataSourceFilter; #endregion #region Save Custom Raster Type if (saveToArt) { IRasterTypeProperties rasterTypeProperties = (IRasterTypeProperties)theRasterType; IRasterTypeEnvironment rasterTypeHelper = new RasterTypeEnvironmentClass(); rasterTypeProperties.Name = customTypeFilePath; IMemoryBlobStream ipBlob = rasterTypeHelper.SaveRasterType(theRasterType); ipBlob.SaveToFile(customTypeFilePath); } #endregion #region Preparing Data Source Crawler Console.WriteLine("Preparing Data Source Crawler"); // Create a new property set to specify crawler properties. IPropertySet crawlerProps = new PropertySetClass(); // Specify a file filter crawlerProps.SetProperty("Filter", dataSourceFilter); // Specify whether to search subdirectories. crawlerProps.SetProperty("Recurse", true); // Specify the source path. crawlerProps.SetProperty("Source", dataSource); // Get the recommended crawler from the raster type based on the specified // properties using the IRasterBuilder interface. // Pass on the Thumbnailtype to the crawler... IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps); #endregion #region Add Rasters try { Console.WriteLine("Adding Rasters"); // Create a AddRaster parameters object. IAddRastersParameters AddRastersArgs = new AddRastersParametersClass(); // Specify the data crawler to be used to crawl the data. AddRastersArgs.Crawler = theCrawler; // Specify the Thumbnail raster type to be used to add the data. AddRastersArgs.RasterType = theRasterType; // Use the mosaic dataset operation interface to add // rasters to the mosaic dataset. theMosaicDatasetOperation.AddRasters(AddRastersArgs, null); } catch (Exception ex) { Console.WriteLine("Error: Add raster Failed." + ex.Message); return; } #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges."); try { // Create a calculate cellsize ranges parameters object. ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass(); // Use the mosaic dataset operation interface to calculate cellsize ranges. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); } catch (Exception ex) { Console.WriteLine("Error: Compute Pixel Size Failed." + ex.Message); return; } #endregion #region Building Boundary Console.WriteLine("Building Boundary"); try { // Create a build boundary parameters object. IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass(); // Set flags that control boundary generation. boundaryArgs.AppendToExistingBoundary = true; // Use the mosaic dataset operation interface to build boundary. theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null); } catch (Exception ex) { Console.WriteLine("Error: Build Boundary Failed." + ex.Message); return; } #endregion #region Report Console.WriteLine("Successfully created MD: " + MosaicDatasetName + ". "); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in TestThumbnailBuilder: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Shutting down."); #endregion } }
private void btnOk_Click(object sender, EventArgs e) { if (listViewEx.CheckedItems.Count == 0) { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未选择对象,无法生成历史!"); return; } Exception err = null; //获取现势库连接信息 SysCommon.Gis.SysGisDataSet sourceSysGisDataSet = new SysCommon.Gis.SysGisDataSet(); switch (comBoxType.Text) { case "SDE": sourceSysGisDataSet.SetWorkspace(txtServer.Text, txtInstance.Text, txtDB.Text, txtUser.Text, txtPassword.Text, txtVersion.Text, out err); break; case "GDB": sourceSysGisDataSet.SetWorkspace(txtDB.Text, SysCommon.enumWSType.GDB, out err); break; case "PDB": sourceSysGisDataSet.SetWorkspace(txtDB.Text, SysCommon.enumWSType.PDB, out err); break; default: break; } if (err != null || sourceSysGisDataSet.WorkSpace == null) { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未设置用户数据库连接或连接失败,请检查!"); return; } //获取历史库连接信息 IPropertySet pPropSet = new PropertySetClass(); IWorkspace pTagetWorkspace = null; try { switch (comboBoxTypeHistory.Text) { case "PDB": AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass(); if (!File.Exists(txtDBHistory.Text)) { FileInfo filePDB = new FileInfo(txtDBHistory.Text); pAccessFact.Create(filePDB.DirectoryName, filePDB.Name, null, 0); } pPropSet.SetProperty("DATABASE", txtDBHistory.Text); pTagetWorkspace = pAccessFact.Open(pPropSet, 0); break; case "GDB": FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass(); DirectoryInfo dirGDB = new DirectoryInfo(txtDBHistory.Text); pFileGDBFact.Create(dirGDB.Parent.FullName, dirGDB.Name.Substring(0, dirGDB.Name.Length - 4), null, 0); pPropSet.SetProperty("DATABASE", txtDBHistory.Text); pTagetWorkspace = pFileGDBFact.Open(pPropSet, 0); break; case "SDE": IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass(); pPropSet.SetProperty("SERVER", txtServerHistory.Text); pPropSet.SetProperty("INSTANCE", txtInstanceHistory.Text); pPropSet.SetProperty("DATABASE", txtDBHistory.Text); pPropSet.SetProperty("USER", txtUserHistory.Text); pPropSet.SetProperty("PASSWORD", txtPasswordHistory.Text); pPropSet.SetProperty("VERSION", txtVersionHistory.Text); pTagetWorkspace = pSdeFact.Open(pPropSet, 0); break; default: break; } } catch (Exception er) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(er, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(er, null, DateTime.Now); } //******************************************************************** } if (pTagetWorkspace == null) { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未设置历史库连接或连接失败,请检查!"); return; } this.Cursor = System.Windows.Forms.Cursors.AppStarting; List <string> lstData = new List <string>(); try { //根据用户数据库结构创建历史库 foreach (ListViewItem aItem in listViewEx.CheckedItems) { if (aItem.Tag.ToString() == "FD") { IFeatureDataset tagetFeatureDataset = null; IFeatureDataset pFeatureDataset = sourceSysGisDataSet.GetFeatureDataset(aItem.Text, out err); if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureDataset, aItem.Text + "_GOH")) { tagetFeatureDataset = (pTagetWorkspace as IFeatureWorkspace).CreateFeatureDataset(aItem.Text + "_GOH", (pFeatureDataset as IGeoDataset).SpatialReference); } else { tagetFeatureDataset = (pTagetWorkspace as IFeatureWorkspace).OpenFeatureDataset(aItem.Text + "_GOH"); } IEnumDataset pEnumDs = pFeatureDataset.Subsets; pEnumDs.Reset(); IDataset pDs = pEnumDs.Next(); while (pDs != null) { IFeatureClass pFeatureClass = pDs as IFeatureClass; if (pFeatureClass != null) { if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, pDs.Name + "_GOH")) { CreateFeatCls(tagetFeatureDataset, pFeatureClass, pDs.Name + "_GOH", out err); } lstData.Add(pDs.Name); } pDs = pEnumDs.Next(); } } else if (aItem.Tag.ToString() == "FC") { IFeatureClass pFeatureClass = sourceSysGisDataSet.GetFeatureClass(aItem.Text, out err); if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, aItem.Text + "_GOH")) { CreateFeatCls(pTagetWorkspace as IFeatureWorkspace, pFeatureClass, aItem.Text + "_GOH", out err); } lstData.Add(aItem.Text); } } } catch (Exception er) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(er, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(er, null, DateTime.Now); } //******************************************************************** this.Cursor = System.Windows.Forms.Cursors.Default; SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "创建历史库结构失败!"); return; } //遍历现势库数据FC进行数据移植 Dictionary <string, string> dicFieldsPair = new Dictionary <string, string>(); dicFieldsPair.Add("OBJECTID", "SourceOID"); Dictionary <string, object> dicValue = new Dictionary <string, object>(); dicValue.Add("FromDate", DateTime.Now.ToString("u")); dicValue.Add("ToDate", DateTime.MaxValue.ToString("u"));//.ToString("YYYY-MM-DD HH:MI:SS")); dicValue.Add("State", 0); (pTagetWorkspace as IWorkspaceEdit).StartEditing(false); bool res = true; progressBarXLay.Maximum = lstData.Count; progressBarXLay.Minimum = 0; progressBarXLay.Value = 0; foreach (string aFeatClsName in lstData) { labelXMemo.Text = "正在进行图层" + aFeatClsName + "..."; Application.DoEvents(); int cnt = 0; int allcnt = 0; IFeatureCursor featureCursor = null; IFeatureClass tagetFeatCls = null; try { featureCursor = sourceSysGisDataSet.GetFeatureCursor(aFeatClsName, "", null, "", out err, out cnt, out allcnt); tagetFeatCls = (pTagetWorkspace as IFeatureWorkspace).OpenFeatureClass(aFeatClsName + "_GOH"); } catch (Exception ex) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(ex, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(ex, null, DateTime.Now); } //******************************************************************** SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", ex.Message); return; } progressBarXFeat.Maximum = cnt; progressBarXFeat.Minimum = 0; progressBarXFeat.Value = 0; ModDBOperator.NewFeatures(tagetFeatCls, featureCursor, dicFieldsPair, dicValue, true, false, progressBarXFeat, out err); Marshal.ReleaseComObject(featureCursor); progressBarXLay.Value++; labelXMemo.Text = ""; Application.DoEvents(); if (err != null) { res = false; break; } } (pTagetWorkspace as IWorkspaceEdit).StopEditing(res); this.Cursor = System.Windows.Forms.Cursors.Default; if (res) { if (m_DbProjectElement != null) { try { XmlElement aElement = m_DbProjectElement.SelectSingleNode(".//内容//历史库//连接信息") as XmlElement; SaveObjDB(aElement, listViewEx.Items[0].Text + "_GOH"); } catch (Exception er) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(er, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(er, null, DateTime.Now); } //******************************************************************** return; } } SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "生成历史库成功!"); this.Close(); } else { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "生成历史库失败!"); } }
/// <summary> /// /// </summary> /// <param name="sShapeFile"></param> /// <param name="sShakeMapID"></param> /// <param name="sFileGDB"></param> /// <param name="sTargetFCName"></param> public bool ImportShapeFileToGeoDB(string sShapeFile, string sShakeMapID, string sFileGDB, string sTargetFCName, StringDictionary sdeSD) { IWorkspace pWS = null; IFeatureClass targetFC; ArcObjects pArcObjects = new ArcObjects(); FileInfo fi; IFeatureClass sourceFC; IFeatureCursor sourceCursor = null; try { // Initialize License m_AOLicenseInitializer = new LicenseInitializer(); m_AOLicenseInitializer.InitializeApplication(new ESRI.ArcGIS.esriSystem.esriLicenseProductCode[] { ESRI.ArcGIS.esriSystem.esriLicenseProductCode.esriLicenseProductCodeEngine }, new ESRI.ArcGIS.esriSystem.esriLicenseExtensionCode[] { }); // Get workspace from FGDB or SDE if (sFileGDB.Length > 0) { pWS = pArcObjects.FileGdbWorkspaceFromPath(sFileGDB); } else { IPropertySet pPropSet = new PropertySetClass(); pPropSet.SetProperty("SERVER", sdeSD["SERVER"]); pPropSet.SetProperty("INSTANCE", sdeSD["INSTANCE"]); pPropSet.SetProperty("DATABASE", sdeSD["DATABASE"]); pPropSet.SetProperty("USER", sdeSD["USER"]); pPropSet.SetProperty("PASSWORD", sdeSD["PASSWORD"]); pPropSet.SetProperty("VERSION", sdeSD["VERSION"]); pWS = pArcObjects.ConnectToTransactionalVersion(pPropSet); } // Make sure we have workspace if (pWS == null) { return(false); } // Get target feature class targetFC = pArcObjects.GetFeatureClass(pWS, sTargetFCName); // Make sure we have target feature class if (targetFC == null) { return(false); } // Set FileInfo object to shape file fi = new FileInfo(sShapeFile); // Make sure we have fileInfo object if (fi == null) { return(false); } // Parse out ShapeFile name without extension string sShapeFileName = fi.Name.Substring(0, fi.Name.Length - (fi.Name.Length - fi.Name.LastIndexOf('.'))); // Get source featue class from shape file sourceFC = GetFeatureClassFromShapefileOnDisk(fi.DirectoryName, sShapeFileName); // Set source feature cursor. sourceCursor = sourceFC.Search(null, false); // Insert features InsertFeaturesUsingCursor(targetFC, sourceCursor, sShakeMapID); return(true); } catch (Exception ex) { return(false); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(sourceCursor); sourceCursor = null; System.Runtime.InteropServices.Marshal.ReleaseComObject(pWS); pWS = null; //Do not make any call to ArcObjects after ShutDownApplication() if (m_AOLicenseInitializer != null) { m_AOLicenseInitializer.ShutdownApplication(); } m_AOLicenseInitializer = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } }
/// <summary> /// Parse ArcGIS MapServer Service /// </summary> /// <param name="urlAGS"></param> public void OpenAGS(string urlAGS) { try { ///Parse the url for MapServer -- get the service url and the service name string strUrl = urlAGS; string[] strUrlParts = strUrl.Split('/'); string strUrlSvr = null; string strSvrName = null; for (int i = 0; i < strUrlParts.Length; i++) { if (strUrlParts[i] == "services") { strUrlSvr = string.Join("/", strUrlParts.Take(i + 1).ToArray()); for (int j = i + 1; j < strUrlParts.Length - 1; j++) { if (strSvrName != null) { strSvrName += "/"; } strSvrName += strUrlParts[j]; } break; } } ///Set up ArcGIS Service connection factory, which includes the list of services IAGSServerConnectionFactory pAGSSvrConnFactory = new AGSServerConnectionFactoryClass(); IPropertySet pPropSet = new PropertySetClass(); pPropSet.SetProperty("URL", strUrlSvr); IAGSServerConnection pAGSSvrConn = pAGSSvrConnFactory.Open(pPropSet, 0); ///Get the list of services IAGSEnumServerObjectName pEnumSOName = pAGSSvrConn.ServerObjectNames; IAGSServerObjectName pAGSSOName = pEnumSOName.Next(); ///Get the specific service with the service name while (pAGSSOName != null) { //Debug.WriteLine(pAGSSOName.Name + ":" + pAGSSOName.Type); if (pAGSSOName.Name == strSvrName && pAGSSOName.Type == "MapServer") { break; } pAGSSOName = pEnumSOName.Next(); } ///Open the specific service IName pName = pAGSSOName as IName; IMapServer pMapServer = pName.Open() as IMapServer; IMapServerLayer pMapSvrLayer = new MapServerLayerClass(); pMapSvrLayer.ServerConnect(pAGSSOName, pMapServer.DefaultMapName); ///Configure the layer before adding it to the map ILayer pLayer = pMapSvrLayer as ILayer; AddLayer(pLayer); } catch (Exception ex) { MessageBox.Show(ex.StackTrace); } }
private IPropertySet method_2(string string_3, string string_4) { IPropertySet set = new PropertySetClass(); if (this.chkSaveManage.Checked) { set.SetProperty("USER", this.txtUserManage.Text.Trim()); } set.SetProperty("Modulus", "dba16ec2c39b37a983b29026dca2859b28cc07bed0a9662bdea17d9fe486fed4d0e2e8a27ca1de05f186d2377da7ced5661e159d10abf5999258d11cb06b2fb3"); if (!this.chkSaveManage.Checked) { set.SetProperty("Exponent", "1001"); } if (this.chkSaveManage.Checked) { if (this.txtUserManage.Text.Trim().Length == 0) { set.SetProperty("HIDEUSERPROPERTY", true); } else { set.SetProperty("HIDEUSERPROPERTY", false); } } else { set.SetProperty("HIDEUSERPROPERTY", true); } set.SetProperty("URL", this.txtMUrl.Text + "/admin"); set.SetProperty("STAGINGFOLDER", this.txtTempFolder.Text); set.SetProperty("USEDEFAULTSTAGINGFOLDER", this.chkUseDefaultFolder.Checked); set.SetProperty("ANONYMOUS", false); set.SetProperty("CONNECTIONMODE", 1); set.SetProperty("SERVERTYPE", 1); set.SetProperty("HTTPTIMEOUT", 60); set.SetProperty("MESSAGEFORMAT", 2); set.SetProperty("SoapUrl", "http://" + string_4 + "/arcgis/services"); set.SetProperty("RestUrl", "http://" + string_4 + "/arcgis/rest"); set.SetProperty("AdminURL", "http://" + string_4 + "/arcgis/admin"); set.SetProperty("AdminTokenUrl", "http://" + string_4 + "/arcgis/admin/generateToken"); set.SetProperty("SupportsRSA", true); if (this.chkSaveManage.Checked) { set.SetProperty("Exponent", "1001"); } if (this.chkSaveManage.Checked) { set.SetProperty("PASSWORD", this.txtPaswordMan.Text); } set.SetProperty("connectionfile", string_3); return(set); }
//根据XML节点获取连接信息 private object GetDBInfoByXMLNode(XmlElement dbElement, string strPath) { try { string strType = dbElement.GetAttribute("类型"); string strServer = dbElement.GetAttribute("服务器"); string strInstance = dbElement.GetAttribute("服务名"); string strDB = dbElement.GetAttribute("数据库"); if (strPath != "") { strDB = strPath + strDB; } string strUser = dbElement.GetAttribute("用户"); string strPassword = dbElement.GetAttribute("密码"); string strVersion = dbElement.GetAttribute("版本"); IPropertySet pPropSet = null; switch (strType.Trim().ToLower()) { case "pdb": pPropSet = new PropertySetClass(); AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass(); if (!File.Exists(strDB)) { FileInfo filePDB = new FileInfo(strDB); pAccessFact.Create(filePDB.DirectoryName, filePDB.Name, null, 0); } pPropSet.SetProperty("DATABASE", strDB); IWorkspace pdbWorkspace = pAccessFact.Open(pPropSet, 0); pAccessFact = null; return(pdbWorkspace); case "gdb": pPropSet = new PropertySetClass(); FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass(); if (!Directory.Exists(strDB)) { DirectoryInfo dirGDB = new DirectoryInfo(strDB); pFileGDBFact.Create(dirGDB.Parent.FullName, dirGDB.Name, null, 0); } pPropSet.SetProperty("DATABASE", strDB); IWorkspace gdbWorkspace = pFileGDBFact.Open(pPropSet, 0); pFileGDBFact = null; return(gdbWorkspace); case "sde": pPropSet = new PropertySetClass(); IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass(); pPropSet.SetProperty("SERVER", strServer); pPropSet.SetProperty("INSTANCE", strInstance); pPropSet.SetProperty("DATABASE", strDB); pPropSet.SetProperty("USER", strUser); pPropSet.SetProperty("PASSWORD", strPassword); pPropSet.SetProperty("VERSION", strVersion); IWorkspace sdeWorkspace = pSdeFact.Open(pPropSet, 0); pSdeFact = null; return(sdeWorkspace); case "access": System.Data.Common.DbConnection dbCon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDB); dbCon.Open(); return(dbCon); //case "oracle": // string strOracle = "Data Source=" + strDB + ";Persist Security Info=True;User ID=" + strUser + ";Password="******";Unicode=True"; // System.Data.Common.DbConnection dbConoracle = new OracleConnection(strOracle); // dbConoracle.Open(); // return dbConoracle; //case "sql": // string strSql = "Data Source=" + strDB + ";Initial Catalog=" + strInstance + ";User ID=" + strUser + ";Password=" + strPassword; // System.Data.Common.DbConnection dbConsql = new SqlConnection(strSql); // dbConsql.Open(); // return dbConsql; default: break; } return(null); } catch (Exception e) { //******************************************************************* //guozheng added //if (ModData.SysLog != null) //{ // ModData.SysLog.Write(e, null, DateTime.Now); //} //else //{ // ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); // ModData.SysLog.Write(e, null, DateTime.Now); //} //******************************************************************** return(null); } }
/// <summary> /// 连接更新目标数据库,获得工作空间与数据集 /// </summary> /// <param name="DesWorkspace">输出的工作空间</param> /// <returns></returns> private bool GetDBDataset(out IWorkspace DesWorkspace) { IWorkspaceFactory pWorkspaceFactory = null; IPropertySet pPropertySet = new PropertySetClass(); comboBoxEx2.Items.Clear(); try { if (comBoxType.SelectedIndex == 1) //SDE库 { pWorkspaceFactory = new SdeWorkspaceFactoryClass(); pPropertySet.SetProperty("SERVER", txtServer.Text); pPropertySet.SetProperty("INSTANCE", txtInstance.Text); pPropertySet.SetProperty("USER", txtUser.Text); pPropertySet.SetProperty("PASSWORD", txtPassWord.Text); pPropertySet.SetProperty("VERSION", txtVersion.Text); } else if (comBoxType.SelectedIndex == 0) //GDB库 { pWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); } else if (comBoxType.SelectedIndex == 2) //PDB库体 { pWorkspaceFactory = new AccessWorkspaceFactoryClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); } DesWorkspace = pWorkspaceFactory.Open(pPropertySet, 0); if (DesWorkspace == null) { return(false); } IEnumDatasetName pEnumDatasetName = DesWorkspace.get_DatasetNames(esriDatasetType.esriDTFeatureDataset); if (pEnumDatasetName == null) { _DesDSName = null; return(true); } IDatasetName pDatasetName = pEnumDatasetName.Next(); while (pDatasetName != null) { comboBoxEx2.Items.Add(pDatasetName.Name); pDatasetName = pEnumDatasetName.Next(); } if (comboBoxEx2.Items.Count > 0) { comboBoxEx2.SelectedIndex = 0; } return(true); } catch (Exception e) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(e, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(e, null, DateTime.Now); } //******************************************************************** DesWorkspace = null; return(false); } }
/// <summary> /// 确定,开始执行创建辅助库操作 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonXOK_Click(object sender, EventArgs e) { this._DesDSName = comboBoxEx2.Text; #region 创建辅助库的表对象 if (comboBoxEx1.SelectedIndex == 0) //本地辅助库 { if (textBoxXServer.Text == "") { SysCommon.Error.ErrorHandle.ShowInform("提示", "请设置辅助库连接!"); return; } if (textBoxXInstance.Text.Trim() == "") { SysCommon.Error.ErrorHandle.ShowInform("提示", "请设置实例名称!"); return; } //初始化更新辅助库体结构和辅助要素类以及图幅结合表 GOFuzingTables InitTable = new GOFuzingTables(textBoxXServer.Text + "\\" + textBoxXInstance.Text + ".mdb"); InitTable.CreateDefaultFeatureClass("ice_CaseScope", false); InitTable.CreateDefaultTables(false, true); InitTable.CreateDefaultFeatureClass("ice_Map", true); InitTable.Dispose(); } else if (comboBoxEx1.SelectedIndex == 1) //远程辅助库 { if (textBoxXServer.Text == "" || textBoxXInstance.Text == "" || textBoxXUser.Text == "" || textBoxXPassword.Text == "") { SysCommon.Error.ErrorHandle.ShowInform("提示", "请设置辅助库连接!"); return; } IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("SERVER", textBoxXServer.Text); pPropertySet.SetProperty("INSTANCE", textBoxXInstance.Text); pPropertySet.SetProperty("USER", textBoxXUser.Text); pPropertySet.SetProperty("PASSWORD", textBoxXPassword.Text); pPropertySet.SetProperty("VERSION", "SDE.DEFAULT"); //初始化更新辅助库体结构和辅助要素类以及图幅结合表 GOFuzingTables InitTable = new GOFuzingTables(pPropertySet); InitTable.CreateDefaultFeatureClass("ice_CaseScope", false); InitTable.CreateDefaultTables(false, true); InitTable.CreateDefaultFeatureClass("ice_Map", true); InitTable.Dispose(); } #endregion ///根据指定的更新目标的库体结构 ///创建更新外部库表结构 /// #region 根据指定的目标库体创建工作库体结构 if (comboBoxEx1.SelectedIndex == 0) //本地外部库 { GOFuzingSpatialTables InitTable = null; if (comBoxType.SelectedIndex == 2) //更新目标位PDB { IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); InitTable = new GOFuzingSpatialTables(textBoxXServer.Text + "\\" + textBoxXInstance.Text + ".gdb", "PDB", pPropertySet); } else if (comBoxType.SelectedIndex == 0) //更新目标为GDB { IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); InitTable = new GOFuzingSpatialTables(textBoxXServer.Text + "\\" + textBoxXInstance.Text + ".gdb", "GDB", pPropertySet); } else if (comBoxType.SelectedIndex == 1) //更新目标位SDE { IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("SERVER", txtServer.Text); pPropertySet.SetProperty("INSTANCE", txtInstance.Text); pPropertySet.SetProperty("USER", txtUser.Text); pPropertySet.SetProperty("PASSWORD", txtPassWord.Text); pPropertySet.SetProperty("VERSION", txtVersion.Text); InitTable = new GOFuzingSpatialTables(textBoxXServer.Text + "\\" + textBoxXInstance.Text + ".gdb", "SDE", pPropertySet); } if (comboBoxEx2.Text == string.Empty) //如果没有指定数据集 { ArrayList FCName = null;; GetFCname("", out FCName); foreach (string var in FCName) { InitTable.CreateDefaultFeatureClass(var, false); InitTable.CreateDefaultFeatureClass(var + "_t", false, true); InitTable.CreateDefaultFeatureClass(var + "_GOH", false, true); } //string[] strFCName=FCName.ToArray(); //for (int i = 0; i < strFCName.Length-1; i++) //{ // InitTable.CreateDefaultFeatureClass(strFCName[i], false); // InitTable.CreateDefaultFeatureClass(strFCName[i]+"_1", false); //} } else //如果指定了数据集 { ArrayList FCName = null; GetFCname(comboBoxEx2.Text, out FCName); Int32 i = 0; foreach (string var in FCName) { if (i > 0) { InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, false); InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, false, "_t"); InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, false, "_GOH", true); } else { InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, true); InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, true, "_t"); InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, true, "_GOH", true); i = i + 1; } } //string[] strFCName=FCName.ToArray(); //for (int i = 0; i < strFCName.Length-1; i++) //{ // InitTable.CreateFeatureClassUnderDS(strFCName[i], comboBoxEx2.Text, false); // InitTable.CreateFeatureClassUnderDS(strFCName[i] + "_1", comboBoxEx2.Text + "_1", false); //} } InitTable.Dispose(); } else if (comboBoxEx1.SelectedIndex == 1) //远程外部库 { GOFuzingSpatialTables InitTable = null; if (comBoxType.SelectedIndex == 2) //更新目标位PDB { IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); ///外部库在SDE上时 IPropertySet pOutPropertySet = new PropertySetClass(); pOutPropertySet.SetProperty("SERVER", textBoxXServer.Text); pOutPropertySet.SetProperty("INSTANCE", textBoxXInstance.Text); pOutPropertySet.SetProperty("USER", textBoxXUser.Text); pOutPropertySet.SetProperty("PASSWORD", textBoxXPassword.Text); pOutPropertySet.SetProperty("VERSION", "SDE.DEFAULT"); InitTable = new GOFuzingSpatialTables(pOutPropertySet, "PDB", pPropertySet); } else if (comBoxType.SelectedIndex == 0) //更新目标为GDB { IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("DATABASE", txtDataBase.Text); ///外部库在SDE上时 IPropertySet pOutPropertySet = new PropertySetClass(); pOutPropertySet.SetProperty("SERVER", textBoxXServer.Text); pOutPropertySet.SetProperty("INSTANCE", textBoxXInstance.Text); pOutPropertySet.SetProperty("USER", textBoxXUser.Text); pOutPropertySet.SetProperty("PASSWORD", textBoxXPassword.Text); pOutPropertySet.SetProperty("VERSION", "SDE.DEFAULT"); InitTable = new GOFuzingSpatialTables(pOutPropertySet, "GDB", pPropertySet); } else if (comBoxType.SelectedIndex == 1) //更新目标位SDE { IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("SERVER", txtServer.Text); pPropertySet.SetProperty("INSTANCE", txtInstance.Text); pPropertySet.SetProperty("USER", txtUser.Text); pPropertySet.SetProperty("PASSWORD", txtPassWord.Text); pPropertySet.SetProperty("VERSION", txtVersion.Text); ///外部库在SDE上时 IPropertySet pOutPropertySet = new PropertySetClass(); pOutPropertySet.SetProperty("SERVER", textBoxXServer.Text); pOutPropertySet.SetProperty("INSTANCE", textBoxXInstance.Text); pOutPropertySet.SetProperty("USER", textBoxXUser.Text); pOutPropertySet.SetProperty("PASSWORD", textBoxXPassword.Text); pOutPropertySet.SetProperty("VERSION", "SDE.DEFAULT"); InitTable = new GOFuzingSpatialTables(pOutPropertySet, "SDE", pPropertySet); } if (comboBoxEx2.Text == string.Empty) //如果没有指定数据集 { ArrayList FCName = null;; GetFCname("", out FCName); foreach (string var in FCName) { InitTable.CreateDefaultFeatureClass(var, false); InitTable.CreateDefaultFeatureClass(var + "_t", false); } //string[] strFCName=FCName.ToArray(); //for (int i = 0; i < strFCName.Length-1; i++) //{ // InitTable.CreateDefaultFeatureClass(strFCName[i], false); // InitTable.CreateDefaultFeatureClass(strFCName[i]+"_1", false); //} } else //如果指定了数据集 { ArrayList FCName = null; GetFCname(comboBoxEx2.Text, out FCName); Int32 i = 0; foreach (string var in FCName) { if (i > 0) { InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, false); InitTable.CreateFeatureClassUnderDS(var + "_t", comboBoxEx2.Text + "_t", false, false); } else { InitTable.CreateFeatureClassUnderDS(var, comboBoxEx2.Text, false, true); InitTable.CreateFeatureClassUnderDS(var + "_t", comboBoxEx2.Text + "_t", false, true); i = i + 1; } } //string[] strFCName=FCName.ToArray(); //for (int i = 0; i < strFCName.Length-1; i++) //{ // InitTable.CreateFeatureClassUnderDS(strFCName[i], comboBoxEx2.Text, false); // InitTable.CreateFeatureClassUnderDS(strFCName[i] + "_1", comboBoxEx2.Text + "_1", false); //} } InitTable.Dispose(); } #endregion ///将更新环境数据库访问方式写入xml文档对象 /// DevComponents.AdvTree.Node pCurNode = m_Hook.ProjectTree.SelectedNode; ///获得树图上选择的工程节点 string pProjectname = pCurNode.Name; System.Xml.XmlNode Projectnode = m_Hook.DBXmlDocument.SelectSingleNode("工程管理/工程[@名称='" + pProjectname + "']"); System.Xml.XmlElement ProjectNodeElement = Projectnode as System.Xml.XmlElement; System.Xml.XmlElement ProjectAidConnEle = ProjectNodeElement.SelectSingleNode(".//更新库/配置库/连接信息") as System.Xml.XmlElement; ///设置数据库连接类型 /// if (comboBoxEx1.SelectedIndex == 0) { ProjectAidConnEle.SetAttribute("类型", "Access"); } else if (comboBoxEx1.SelectedIndex == 1) { ProjectAidConnEle.SetAttribute("类型", "Oracle"); } ///设置具体连接方式 /// if (comboBoxEx1.SelectedIndex == 0) { string text = textBoxXServer.Text + "\\" + textBoxXInstance.Text + ".mdb"; ProjectAidConnEle.SetAttribute("数据库", text); } else if (comboBoxEx1.SelectedIndex == 1) { ProjectAidConnEle.SetAttribute("数据库", textBoxXServer.Text); ProjectAidConnEle.SetAttribute("用户", textBoxXUser.Text); ProjectAidConnEle.SetAttribute("密码", textBoxXPassword.Text); } System.Xml.XmlElement ProjectTempDBConnEle = ProjectNodeElement.SelectSingleNode(".//更新库/数据库/连接信息") as System.Xml.XmlElement; ProjectTempDBConnEle.SetAttribute("类型", "GDB"); ProjectTempDBConnEle.SetAttribute("数据库", textBoxXServer.Text + "\\" + textBoxXInstance.Text + ".gdb"); System.Xml.XmlElement CurDBEle = ProjectTempDBConnEle.SelectSingleNode("库体[@类型='现势']") as System.Xml.XmlElement; CurDBEle.SetAttribute("名称", comboBoxEx2.Text); System.Xml.XmlElement TempDBEle = ProjectTempDBConnEle.SelectSingleNode("库体[@类型='工作']") as System.Xml.XmlElement; TempDBEle.SetAttribute("名称", comboBoxEx2.Text + "_t"); System.Xml.XmlElement HisDBEle = ProjectTempDBConnEle.SelectSingleNode("库体[@类型='历史']") as System.Xml.XmlElement; HisDBEle.SetAttribute("名称", comboBoxEx2.Text + "_GOH"); m_Hook.DBXmlDocument.Save(ModData.v_projectXML); //释放类成员 if (_UpadateDesWorkspace != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(_UpadateDesWorkspace); } SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "更新环境初始化完成!"); this.Close(); }
private void btnTestConnection_Click(object sender, EventArgs e) { if ((this.radioGroup1.SelectedIndex == 0) || (this.radioGroup1.SelectedIndex == 1)) { IPropertySet connectionProperties = new PropertySetClass(); string str = this.txtServer.Text.Trim(); connectionProperties.SetProperty("DB_CONNECTION_PROPERTIES", str); if (this.radioGroup1.SelectedIndex == 0) { connectionProperties.SetProperty("DBCLIENT", "sqlserver"); connectionProperties.SetProperty("Database", this.cboDatabase.Text); } else { connectionProperties.SetProperty("DBCLIENT", "oracle"); } if (this.chkIsOperateSystemYZ.Checked) { connectionProperties.SetProperty("AUTHENTICATION_MODE", "OSA"); } else { connectionProperties.SetProperty("AUTHENTICATION_MODE", "DBMS"); connectionProperties.SetProperty("User", this.txtUser.Text); connectionProperties.SetProperty("Password", this.txtPassword.Text); } IWorkspaceFactory factory = new SdeWorkspaceFactoryClass(); try { AppConfig.m_pWorkspace = factory.Open(connectionProperties, 0); MessageBox.Show("空间数据库连接成功!", "测试连接"); } catch (Exception exception) { if (exception is COMException) { uint errorCode = (uint)(exception as COMException).ErrorCode; if ((errorCode == 2147751273) || (errorCode == 2147751169)) { MessageBox.Show("无法连接到空间数据库,请检查配置参数是否正确!", "测试连接"); } else if (errorCode == 2147751274) { MessageBox.Show("该服务器上的SDE没有启动,请启动服务器上的SDE后在测试!", "测试连接"); } else if (errorCode == 2147500037) { MessageBox.Show("无法连接到空间数据库,请检查配置参数是否正确!", "测试连接"); } else { MessageBox.Show(exception.Message, "测试连接"); } } else { MessageBox.Show(exception.Message, "测试连接"); } } } else if (this.txtMDB.Text.Trim().Length == 0) { MessageBox.Show("请输入个人数据库"); } else if (!File.Exists(this.txtMDB.Text.Trim())) { MessageBox.Show("指定的个人数据库不存在"); } else { MessageBox.Show("空间数据库连接成功!", "测试连接"); } }
/// <summary> /// This method searches for the record of the given zipcode and retunes the information as a PropertySet. /// </summary> /// <param name="zipCode"></param> /// <returns>a PropertySet encapsulating the weather information for the given weather item.</returns> public IPropertySet GetWeatherItem(long zipCode) { DataRow r = m_table.Rows.Find(zipCode); if(null == r) return null; IPropertySet propSet = new PropertySetClass(); propSet.SetProperty( "ID", r[0]); propSet.SetProperty( "ZIPCODE", r[1]); propSet.SetProperty( "CITYNAME", r[2]); propSet.SetProperty( "LAT", r[3]); propSet.SetProperty( "LON", r[4]); propSet.SetProperty( "TEMPERATURE", r[5]); propSet.SetProperty( "CONDITION", r[6]); propSet.SetProperty( "ICONNAME", r[7]); propSet.SetProperty( "ICONID", r[8]); propSet.SetProperty( "DAY", r[9]); propSet.SetProperty( "DATE", r[10]); propSet.SetProperty( "LOW", r[11]); propSet.SetProperty( "HIGH", r[12]); propSet.SetProperty( "UPDATEDATE", r[14]); return propSet; }
//加载地图图层。 public static void LoadSdeLayer(AxMapControl MapCtr, bool ChkSdeLinkModle) { //定义一个属性 IPropertySet Propset = new PropertySetClass(); if (ChkSdeLinkModle == true) // 采用SDE连接 { //设置数据库服务器名,服务器所在的IP地址 Propset.SetProperty("SERVER", "my"); //设置SDE的端口,这是安装时指定的,默认安装时"port:5151" Propset.SetProperty("INSTANCE", "port:5151"); //SDE的用户名 Propset.SetProperty("USER", "sa"); //密码 Propset.SetProperty("PASSWORD", "sa"); //设置数据库的名字,只有SQL Server Informix 数据库才需要设置 Propset.SetProperty("DATABASE", "sde"); //SDE的版本,在这为默认版本 Propset.SetProperty("VERSION", "SDE.DEFAULT"); } else // 直接连接 { //设置数据库服务器名,如果是本机可以用"sde:sqlserver:." Propset.SetProperty("INSTANCE", "sde:sqlserver:zhpzh"); //SDE的用户名 Propset.SetProperty("USER", "sa"); //密码 Propset.SetProperty("PASSWORD", "sa"); //设置数据库的名字,只有SQL Server Informix 数据库才需要设置 Propset.SetProperty("DATABASE", "sde"); //SDE的版本,在这为默认版本 Propset.SetProperty("VERSION", "SDE.DEFAULT"); } //定义一个工作空间,并实例化为SDE的工作空间 IWorkspaceFactory Fact = new SdeWorkspaceFactoryClass(); //打开SDE工作空间,并转化为地物工作空间 IFeatureWorkspace Workspace = (IFeatureWorkspace)Fact.Open(Propset, 0); /*定义一个地物类,并打开SDE中的管点地物类,写的时候一定要写全.如SDE中有一个管点层,你不能写成IFeatureClass Fcls = Workspace.OpenFeatureClass ("管点");这样,一定要写成下边的样子.*/ IFeatureClass Fcls = Workspace.OpenFeatureClass("sde.dbo.管点"); IFeatureLayer Fly = new FeatureLayerClass(); Fly.FeatureClass = Fcls; MapCtr.Map.AddLayer(Fly); MapCtr.ActiveView.Refresh(); }
/******************************************************************************** * Function name : makeMap * Description : makes the animal movement maps. One for each animal. * Return type : void * Argument : string shapePath * Argument : string shapeFileName * ********************************************************************************/ public bool makeMap(string shapePath, string shapeFileName, IGeometryDef inGeoDef) { bool success = true; try { shapePath = shapePath + "\\" + shapeFileName; //C:\test\2013\0\0 if (!loadFromBackup) { Directory.CreateDirectory(shapePath); this.myPath = shapePath; } IWorkspaceFactory shpWkspFactory = new ShapefileWorkspaceFactoryClass(); IPropertySet connectionProperty = new PropertySetClass(); IGeometryDefEdit geoDef = new GeometryDefClass(); IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; connectionProperty.SetProperty("DATABASE", shapePath); shapeWksp = (IFeatureWorkspace)shpWkspFactory.Open(connectionProperty, 0); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "OBJECTID"; fieldEdit.AliasName_2 = "OBJECTID"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "SHAPE"; fieldEdit.IsNullable_2 = true; fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; fieldEdit.GeometryDef_2 = inGeoDef; fieldEdit.Required_2 = true; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "ID"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "CurrTime"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger; fieldEdit.DefaultValue_2 = 0; fieldsEdit.AddField(fieldEdit); fieldEdit = new FieldClass(); fieldEdit.Name_2 = "Available"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger; fieldEdit.DefaultValue_2 = 0; fieldsEdit.AddField(fieldEdit); //If loading from backup open the feature class rather than create a new one if (loadFromBackup) { this.mySelf = this.getShapeFile(shapePath); //this.mySelf = shapeWksp.OpenFeatureClass(shapePath); } else { this.mySelf = shapeWksp.CreateFeatureClass(shapeFileName, fieldsEdit, null, null, esriFeatureType.esriFTSimple, "Shape", ""); } System.Runtime.InteropServices.Marshal.ReleaseComObject(shpWkspFactory); System.Runtime.InteropServices.Marshal.ReleaseComObject(connectionProperty); System.Runtime.InteropServices.Marshal.ReleaseComObject(geoDef); System.Runtime.InteropServices.Marshal.ReleaseComObject(fields); } catch (System.Exception ex) { success = false; if (ex.Source == "ESRI.ArcGIS.Geodatabase") { mErrMessage = "That Directory is full with maps already"; throw new System.Exception("That Directory is full with maps already"); } eLog.Debug(ex); } return(success); }
//////////////////////////////////////////////////////////////////////// // METHOD: CreateDependencyOnParentJob private void CreateDependencyOnParentJob(IJTXJobDependencies dependencyManager, IJTXJob2 pParentJob, int childJobID) { IJTXJobDependency dependency = dependencyManager.CreateDependency(pParentJob.ID); dependency.DepJobID = childJobID; dependency.DepOnType = jtxDependencyType.jtxDependencyTypeStatus; IJTXStatus statusType = null; if (!m_paramHasStatusType) statusType = m_ipDatabase.ConfigurationManager.GetStatus("Closed"); else statusType = m_ipDatabase.ConfigurationManager.GetStatus(m_paramStatusType); dependency.DepOnValue = statusType.ID; dependency.HeldOnType = jtxDependencyType.jtxDependencyTypeStep; IJTXWorkflowExecution parentWorkflow = pParentJob as IJTXWorkflowExecution; int[] currentSteps = parentWorkflow.GetCurrentSteps(); int dependentStep = currentSteps[0]; if (m_paramDependNextStep) { IJTXWorkflowConfiguration workflowConf = pParentJob as IJTXWorkflowConfiguration; try { dependentStep = workflowConf.GetAllNextSteps(currentSteps[0])[0]; } catch (IndexOutOfRangeException) { MessageBox.Show(Properties.Resources.NoNextStep, Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } dependency.HeldOnValue = dependentStep; dependency.Store(); IPropertySet props = new PropertySetClass(); props.SetProperty("[DEPENDENCY]", dependency.ID); JobUtilities.LogJobAction(m_ipDatabase, pParentJob, Constants.ACTTYPE_ADD_DEPENDENCY, "", props); }
//自定义汇总统计 //根据连接字符串获取工作空间 //此处连接字符串是固定格式的连接串 Server|Service|Database|User|Password|Version private static IWorkspace GetWorkSpacefromConninfo(string conninfostr, int type) { //added by chulili 20111109 添加保护 if (conninfostr == "") { return(null); } if (type < 0) { return(null); } //end added by chulili 20111109 int index1 = conninfostr.IndexOf("|"); int index2 = conninfostr.IndexOf("|", index1 + 1); int index3 = conninfostr.IndexOf("|", index2 + 1); int index4 = conninfostr.IndexOf("|", index3 + 1); int index5 = conninfostr.IndexOf("|", index4 + 1); int index6 = conninfostr.IndexOf("|", index5 + 1); IPropertySet pPropSet = new PropertySetClass(); IWorkspaceFactory pWSFact = null; string sServer = ""; string sService = ""; string sDatabase = ""; string sUser = ""; string sPassword = ""; string strVersion = ""; switch (type) { case 1: //mdb pWSFact = new AccessWorkspaceFactoryClass(); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); break; case 2: //gdb pWSFact = new FileGDBWorkspaceFactoryClass(); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); break; case 3: //sde pWSFact = new SdeWorkspaceFactoryClass(); sServer = conninfostr.Substring(0, index1); sService = conninfostr.Substring(index1 + 1, index2 - index1 - 1); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); sUser = conninfostr.Substring(index3 + 1, index4 - index3 - 1); sPassword = conninfostr.Substring(index4 + 1, index5 - index4 - 1); strVersion = conninfostr.Substring(index5 + 1, index6 - index5 - 1); break; } pPropSet.SetProperty("SERVER", sServer); pPropSet.SetProperty("INSTANCE", sService); pPropSet.SetProperty("DATABASE", sDatabase); pPropSet.SetProperty("USER", sUser); pPropSet.SetProperty("PASSWORD", sPassword); pPropSet.SetProperty("VERSION", strVersion); try { IWorkspace pWorkspace = pWSFact.Open(pPropSet, 0); return(pWorkspace); } catch { return(null); } }
public void UpdateAssetsTest() { RuntimeManager.Bind(ProductCode.Desktop); (new AoInitializeClass()).Initialize(esriLicenseProductCode.esriLicenseProductCodeStandard); IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("Server", "RJMSDDBT02"); propertySet.SetProperty("Instance", "sde:oracle11g:gisdevl"); propertySet.SetProperty("Database", "GISDEVL"); propertySet.SetProperty("user", "MSD"); propertySet.SetProperty("password", "jc_tc1954"); propertySet.SetProperty("version", "MSD.QC"); int flag = 0; try { IWorkspace workspaceName = (new SdeWorkspaceFactoryClass()).Open(propertySet, 0); IVersionedWorkspace versionedWorkspace = (IVersionedWorkspace)workspaceName; IEnumVersionInfo enumVersionInfo = versionedWorkspace.Versions; enumVersionInfo.Reset(); IVersionInfo existversionInfo = enumVersionInfo.Next(); while (existversionInfo != null) { if (!existversionInfo.VersionName.Trim().Equals("MSD.DTS_EDIT")) { existversionInfo = enumVersionInfo.Next(); } else { versionedWorkspace.FindVersion("MSD.DTS_EDIT").Delete(); flag = 1; break; } } enumVersionInfo.Reset(); IVersion version = (IVersion)((IFeatureWorkspace)workspaceName); string name = version.VersionInfo.VersionName; IVersion dtsVersion = version.CreateVersion("DTS_EDIT"); dtsVersion.Access = esriVersionAccess.esriVersionAccessPublic; dtsVersion.Description = "Update DTS to MSD Ownership via DTS app"; if (dtsVersion.VersionName.Contains("DTS_EDIT")) { IMultiuserWorkspaceEdit multiuserWorkspaceEdit = (IMultiuserWorkspaceEdit)dtsVersion; IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)dtsVersion; IVersionEdit4 versionEdit = (IVersionEdit4)workspaceEdit; if (multiuserWorkspaceEdit.SupportsMultiuserEditSessionMode(esriMultiuserEditSessionMode.esriMESMVersioned)) { multiuserWorkspaceEdit.StartMultiuserEditing(esriMultiuserEditSessionMode.esriMESMVersioned); versionEdit.Reconcile4("MSD.QC", true, false, false, false); workspaceEdit.StartEditOperation(); IFeature featureEdit = ((IFeatureWorkspace)workspaceEdit).OpenFeatureClass("SWRAINGAUGE").GetFeature(330); // Convert.ToString(featureEdit[6]); Convert.ToString(featureEdit.Value[6]); int Totalfield = featureEdit.Fields.FieldCount; int ownershipindex = featureEdit.Fields.FindField("OWNERSHIP"); int lastmodifieddtindex = featureEdit.Fields.FindField("LAST_MODIFIED_DATE"); DateTime lastmodifieddt = DateTime.Now.Date; //featureEdit[ownershipindex] = "1"; //featureEdit[lastmodifieddtindex] = lastmodifieddt.Date; featureEdit.Value[ownershipindex] = "1"; featureEdit.Value[lastmodifieddtindex] = lastmodifieddt.Date; featureEdit.Store(); if (versionEdit.CanPost()) { versionEdit.Post("MSD.QC"); } workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); } } } catch (COMException cOMException) { if (cOMException.ErrorCode == -2147217147) { } } catch (Exception exception) { } }
private void btnOk_Click(object sender, EventArgs e) { if (txtProjectName.Text == "") { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("信息提示", "请填写输出文件名称 !"); return; } if (!Directory.Exists(txtSavePath.Text.Trim())) { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("信息提示", "请选择保存路径 !"); return; } if (listViewEx.CheckedItems.Count == 0) { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("信息提示", "请选择数据版本信息 !"); return; } string WorkSpacePath = txtSavePath.Text.Trim() + "\\" + txtProjectName.Text.Trim(); IPropertySet pPropSet = new PropertySetClass(); IWorkspace pTagetWorkspace = null; try { switch (comBoxType.Tag.ToString().Trim()) { case "PDB": AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass(); if (!File.Exists(WorkSpacePath + ".mdb")) { pAccessFact.Create(txtSavePath.Text, txtProjectName.Text, null, 0); } pPropSet.SetProperty("DATABASE", WorkSpacePath + ".mdb"); pTagetWorkspace = pAccessFact.Open(pPropSet, 0); pAccessFact = null; pPropSet = null; break; case "GDB": FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass(); if (!Directory.Exists(WorkSpacePath + ".gdb")) { pFileGDBFact.Create(txtSavePath.Text, txtProjectName.Text, null, 0); } pPropSet.SetProperty("DATABASE", WorkSpacePath + ".gdb"); pTagetWorkspace = pFileGDBFact.Open(pPropSet, 0); pFileGDBFact = null; pPropSet = null; break; default: break; } } catch (Exception er) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(er, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(er, null, DateTime.Now); } //******************************************************************** } if (pTagetWorkspace == null) { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未设置输出库连接或连接失败,请检查!"); return; } this.Cursor = System.Windows.Forms.Cursors.AppStarting; Exception err = null; bool res = true; List <IFeatureLayer> lstFeatLay = new List <IFeatureLayer>(); //根据历史图层创建输出数据图层结构 for (int i = 0; i < Map.LayerCount; i++) { //cyf 20110706 add ILayer mLayer = Map.get_Layer(i); if (mLayer is IGroupLayer) { ICompositeLayer pComLayer = mLayer as ICompositeLayer; for (int j = 0; j < pComLayer.Count; j++) { IFeatureLayer featLay = pComLayer.get_Layer(j) as IFeatureLayer; if (featLay == null) { continue; } if (!(featLay.FeatureClass as IDataset).Name.EndsWith("_GOH")) { continue; } lstFeatLay.Add(featLay); if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, featLay.Name))//(featLay.FeatureClass as IDataset).Name { if (!CreateFeatCls(pTagetWorkspace as IFeatureWorkspace, featLay.FeatureClass, featLay.Name, out err)) { res = false; featLay = null; pComLayer = null; mLayer = null; break; } } } }//end else { IFeatureLayer featLay = Map.get_Layer(i) as IFeatureLayer; if (featLay == null) { continue; } if (!(featLay.FeatureClass as IDataset).Name.EndsWith("_GOH")) { continue; } lstFeatLay.Add(featLay); if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, featLay.Name))//(featLay.FeatureClass as IDataset).Name { if (!CreateFeatCls(pTagetWorkspace as IFeatureWorkspace, featLay.FeatureClass, featLay.Name, out err)) { res = false; featLay = null; mLayer = null; break; } } } } if (res == false) { this.Cursor = System.Windows.Forms.Cursors.Default; SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "创建输出库结构失败!"); System.Runtime.InteropServices.Marshal.ReleaseComObject(pTagetWorkspace); pTagetWorkspace = null; lstFeatLay.Clear(); lstFeatLay = null; try { Directory.Delete(txtSavePath.Text + "\\" + txtProjectName.Text + ".gdb", true); } catch (Exception err2) { } return; } StringBuilder sb = new StringBuilder(); foreach (ListViewItem aItem in listViewEx.CheckedItems) { if (sb.Length != 0) { sb.Append("or"); } else { sb.Append("("); } sb.Append("(FromDate<='" + aItem.Text + "' and ToDate>'" + aItem.Text + "')"); } sb.Append(")"); //遍历数据FC进行数据移植 (pTagetWorkspace as IWorkspaceEdit).StartEditing(false); progressBarXLay.Maximum = lstFeatLay.Count; progressBarXLay.Minimum = 0; progressBarXLay.Value = 0; foreach (IFeatureLayer aFeatLay in lstFeatLay) { labelXMemo.Text = aFeatLay.FeatureClass.AliasName + "..."; Application.DoEvents(); StringBuilder newSB = new StringBuilder(); newSB.Append(sb.ToString()); if (m_Sel) { int fdIndex = aFeatLay.FeatureClass.Fields.FindField("SourceOID"); if (fdIndex == -1) { continue; } IFeatureLayerDefinition featLayDefTemp = aFeatLay as IFeatureLayerDefinition; IEnumIDs pEnumIDs = featLayDefTemp.DefinitionSelectionSet.IDs; int ID = pEnumIDs.Next(); StringBuilder sbTemp = new StringBuilder(); while (ID != -1) { IFeature pFeat = aFeatLay.FeatureClass.GetFeature(ID); if (sbTemp.Length != 0) { sbTemp.Append(","); } sbTemp.Append(pFeat.get_Value(fdIndex).ToString()); ID = pEnumIDs.Next(); } newSB.Append(" and SourceOID in (" + sbTemp.ToString() + ")"); } IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = newSB.ToString(); IFeatureCursor featureCursor = aFeatLay.FeatureClass.Search(queryFilter, false); progressBarXFeat.Maximum = aFeatLay.FeatureClass.FeatureCount(queryFilter); progressBarXFeat.Minimum = 0; progressBarXFeat.Value = 0; try { //cyf 20110706 modify:去掉用户名 string pFeaLayerName = aFeatLay.Name.Trim(); if (pFeaLayerName.Contains(".")) { pFeaLayerName = pFeaLayerName.Substring(pFeaLayerName.IndexOf('.') + 1); } //end IFeatureClass tagetFeatCls = (pTagetWorkspace as IFeatureWorkspace).OpenFeatureClass(pFeaLayerName);//(aFeatLay.FeatureClass as IDataset).Name ModDBOperator.NewFeatures(tagetFeatCls, featureCursor, null, null, true, false, progressBarXFeat, out err); } catch (Exception ex) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(ex, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(ex, null, DateTime.Now); } //******************************************************************** SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "入库失败!"); return; } Marshal.ReleaseComObject(featureCursor); progressBarXLay.Value++; labelXMemo.Text = ""; Application.DoEvents(); if (err != null) { res = false; break; } } (pTagetWorkspace as IWorkspaceEdit).StopEditing(res); this.Cursor = System.Windows.Forms.Cursors.Default; if (res) { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "提取成功!"); this.Close(); } else { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "提取失败!"); } }
public IWorkspace CreateWorkspaceSDE(string server, string instance, string database, string version, string user, string password) { IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass(); IPropertySet propertySet = new PropertySetClass(); //create version for editting //TnUtilities utilities = new TnUtilities(); IWorkspace workspace = null; //utilities.StartService("esri_sde", 2000); propertySet.SetProperty("SERVER", server); propertySet.SetProperty("INSTANCE", instance); propertySet.SetProperty("DATABASE", database); propertySet.SetProperty("VERSION", version); propertySet.SetProperty("USER", user); propertySet.SetProperty("PASSWORD", password); //if (authentication_mode != "OSA" && authentication_mode != "osa") //{ // propertySet.SetProperty("USER", user); // propertySet.SetProperty("PASSWORD", password); //} //else if (authentication_mode == "OSA" || authentication_mode == "osa") //{ // propertySet.SetProperty("AUTHENTICATION_MODE", authentication_mode); //} //else //{ // MessageBox.Show("Chua xac dinh duoc Authentication_mode"); //} //if (version == "sde.DEFAULT") //{ // Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory"); // workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); //} //if (version == "dbo.DEFAULT") //{ // propertySet.SetProperty("VERSION", version); //} //else //{ Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory"); workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); //} try { workspace = workspaceFactory.Open(propertySet, 0); } catch (Exception ex){MessageBox.Show(string.Format("line 94 WorkspaceManagement:\n {0}",ex)); } //if (workspace.IsBeingEdited() != true) //{ // workspaceEdit.StartEditing(true); // workspaceEdit.StartEditOperation(); //} return workspace; }
public static IWorkspace GetSDEWorkspace(string sServerName, string sInstancePort, string sUserName, string sPassword, string sVersionName) { IPropertySet set = new PropertySetClass(); set.SetProperty("Server", sServerName); set.SetProperty("Instance", sInstancePort); set.SetProperty("User", sUserName); set.SetProperty("password", sPassword); set.SetProperty("version", sVersionName); SdeWorkspaceFactoryClass class2 = new SdeWorkspaceFactoryClass(); try { return class2.Open(set, 0); } catch (Exception ex) { return null; } }
public static void AddIdahoWms(List <string> idahoIds, string groupLayerName, string token) { // Don't do anything if the aren't any idaho id's to work with if (idahoIds.Count <= 0) { return; } IGroupLayer groupLayer = new GroupLayerClass(); groupLayer.Name = groupLayerName; foreach (var id in idahoIds) { var wmsMapLayer = new WMSMapLayerClass(); // create and configure wms connection name, this is used to store the connection properties IWMSConnectionName pConnName = new WMSConnectionNameClass(); IPropertySet propSet = new PropertySetClass(); // create the idaho wms url var idahoUrl = string.Format( "http://idaho.geobigdata.io/v1/wms/idaho-images/{0}/{1}/mapserv?", id, token); Jarvis.Logger.Info("Adding WMS Layer to: " + idahoUrl); // setup the arcmap connection properties propSet.SetProperty("URL", idahoUrl); pConnName.ConnectionProperties = propSet; //uses the name information to connect to the service IDataLayer dataLayer = wmsMapLayer; try { dataLayer.Connect((IName)pConnName); } catch (Exception e) { Jarvis.Logger.Error("Problems connecting to WMS: " + e.Message); } // get wms service description var serviceDesc = wmsMapLayer.IWMSGroupLayer_WMSServiceDescription; ILayer wmsLayer = null; // add layers for the wms currently there will only be one. for (var i = 0; i <= serviceDesc.LayerDescriptionCount - 1; i++) { var layerDesc = serviceDesc.LayerDescription[i]; var grpLayer = wmsMapLayer.CreateWMSGroupLayers(layerDesc); for (var j = 0; j <= grpLayer.Count - 1; j++) { wmsLayer = wmsMapLayer; wmsMapLayer.Name = id; } } // turn on sub layers, add it to arcmap and move it to top of TOC SublayerVisibleOn(wmsLayer); groupLayer.Add(wmsLayer); } // turn on sub layers, add it to arcmap and move it to top of TOC ArcMap.Document.AddLayer(groupLayer); ArcMap.Document.FocusMap.MoveLayer(groupLayer, 0); }
public azgsSqlDatabaseChooser() { InitializeComponent(); // Populate the listbox // Build a DataTable to bind to the listbox control DataTable projectTable = new DataTable(); DataColumn projName = new DataColumn(); projName.ColumnName = "ProjectName"; projName.DataType = typeof(string); DataColumn dbName = new DataColumn(); dbName.ColumnName = "DatabaseName"; dbName.DataType = typeof(string); projectTable.Columns.Add(projName); projectTable.Columns.Add(dbName); // Populate the DataTable - Right now this is pinging a DB on malachite IPropertySet connectionProperties = new PropertySetClass(); connectionProperties.SetProperty("SERVER", "malachite\\azgsgeodatabases"); connectionProperties.SetProperty("INSTANCE", "sde:sqlserver:malachite\\azgsgeodatabases"); connectionProperties.SetProperty("DATABASE", "AzgsIndex"); connectionProperties.SetProperty("AUTHENTICATION_MODE", "OSA"); connectionProperties.SetProperty("VERSION", "dbo.Default"); try { IWorkspaceFactory wsFact = new SdeWorkspaceFactoryClass(); IWorkspace theWs = wsFact.Open(connectionProperties, 0); // Open the table in the repository database ITable ProjectListingsTable = commonFunctions.OpenTable(theWs, "ProjectDatabases"); // Get all the records into a sorted cursor ITableSort projSorter = new TableSortClass(); projSorter.Table = ProjectListingsTable; projSorter.QueryFilter = null; projSorter.Fields = "ProjectName"; projSorter.set_Ascending("ProjectName", true); projSorter.Sort(null); ICursor projCur = projSorter.Rows; //ProjectListingsTable.Search(null, false); // Loop through the cursor and add records to the DataTable IRow projRow = projCur.NextRow(); while (projRow != null) { projectTable.Rows.Add((String)projRow.get_Value(ProjectListingsTable.FindField("ProjectName")), (String)projRow.get_Value(ProjectListingsTable.FindField("DatabaseName"))); projRow = projCur.NextRow(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(projCur); // Bind the DataTable to the control this.listProjects.DataSource = projectTable; this.listProjects.DisplayMember = "ProjectName"; this.listProjects.ValueMember = "DatabaseName"; this.listProjects.SelectedItem = null; this.listVersions.DataSource = null; } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace); return; } }
/// <summary> /// Create a Mosaic Dataset in the geodatabase provided using the parameters defined by MDParamaters. /// </summary> /// <param name="gdbWorkspace">Geodatabase to create the Mosaic dataser in.</param> public void CreateMosaicDataset(IWorkspace gdbWorkspace) { try { #region Global Declarations IMosaicDataset theMosaicDataset = null; IMosaicDatasetOperation theMosaicDatasetOperation = null; IMosaicWorkspaceExtensionHelper mosaicExtHelper = null; IMosaicWorkspaceExtension mosaicExt = null; #endregion #region CreateMosaicDataset try { Console.WriteLine("Create Mosaic Dataset: " + MDParameters.mosaicDatasetName + ".amd"); /// Setup workspaces. /// Create Srs ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); // Create the mosaic dataset creation parameters object. ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass(); // Set the number of bands for the mosaic dataset. // If defined as zero leave defaults if (MDParameters.mosaicDatasetBands != 0) { creationPars.BandCount = MDParameters.mosaicDatasetBands; } // Set the pixel type of the mosaic dataset. // If defined as unknown leave defaults if (MDParameters.mosaicDatasetBits != rstPixelType.PT_UNKNOWN) { creationPars.PixelType = MDParameters.mosaicDatasetBits; } // Create the mosaic workspace extension helper class. mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass(); // Find the right extension from the workspace. mosaicExt = mosaicExtHelper.FindExtension(gdbWorkspace); // Default is none. if (MDParameters.productDefinitionKey.ToLower() != "none") { // Set the product definition keyword and properties. // (The property is called band definition keyword and band properties in the object). ((ICreateMosaicDatasetParameters2)creationPars).BandDefinitionKeyword = MDParameters.productDefinitionKey; MDParameters.productDefinitionProps = SetBandProperties(MDParameters.productDefinitionKey); if (MDParameters.productDefinitionProps.Count == 0) { Console.WriteLine("Setting production definition properties failed."); return; } ((ICreateMosaicDatasetParameters2)creationPars).BandProperties = MDParameters.productDefinitionProps; } // Use the extension to create a new mosaic dataset, supplying the // spatial reference and the creation parameters object created above. theMosaicDataset = mosaicExt.CreateMosaicDataset(MDParameters.mosaicDatasetName, MDParameters.mosaicDatasetSrs, creationPars, MDParameters.configKeyword); } catch (Exception exc) { Console.WriteLine("Exception Caught while creating Mosaic Dataset: " + exc.Message); return; } #endregion #region OpenMosaicDataset Console.WriteLine("Opening Mosaic Dataset"); theMosaicDataset = null; // Use the extension to open the mosaic dataset. theMosaicDataset = mosaicExt.OpenMosaicDataset(MDParameters.mosaicDatasetName); // The mosaic dataset operation interface is used to perform operations on // a mosaic dataset. theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset); #endregion #region Preparing Raster Type Console.WriteLine("Preparing Raster Type"); // Create a Raster Type Name object. IRasterTypeName theRasterTypeName = new RasterTypeNameClass(); // Assign the name of the Raster Type to the name object. // The Name field accepts a path to an .art file as well // the name for a built in Raster Type. theRasterTypeName.Name = MDParameters.rasterTypeName; // Use the Open function from the IName interface to get the Raster Type object. IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open()); if (theRasterType == null) { Console.WriteLine("Raster Type not found " + MDParameters.rasterTypeName); } // Set the URI Filter on the loaded raster type. if (MDParameters.rasterTypeProductFilter != "") { // Get the supported URI filters from the raster type object using the // raster type properties interface. IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters; IItemURIFilter productFilter = null; for (int i = 0; i < mySuppFilters.Count; ++i) { // Set the desired filter from the supported filters. productFilter = (IItemURIFilter)mySuppFilters.get_Element(i); if (productFilter.Name == MDParameters.rasterTypeProductFilter) { theRasterType.URIFilter = productFilter; } } } // Enable the correct templates in the raster type. string[] rasterProductNames = MDParameters.rasterTypeProductName.Split(';'); bool enableTemplate = false; if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != "")) { // Get the supported item templates from the raster type. IItemTemplateArray templateArray = theRasterType.ItemTemplates; for (int i = 0; i < templateArray.Count; ++i) { // Go through the supported item templates and enable the ones needed. IItemTemplate template = templateArray.get_Element(i); enableTemplate = false; for (int j = 0; j < rasterProductNames.Length; ++j) { if (template.Name == rasterProductNames[j]) { enableTemplate = true; } } if (enableTemplate) { template.Enabled = true; } else { template.Enabled = false; } } } if (MDParameters.dataSourceSrs != null) { ((IRasterTypeProperties)theRasterType).SynchronizeParameters.DefaultSpatialReference = MDParameters.dataSourceSrs; } #endregion #region Add DEM To Raster Type if (MDParameters.rasterTypeAddDEM && ((IRasterTypeProperties)theRasterType).SupportsOrthorectification) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile( System.IO.Path.GetDirectoryName(MDParameters.rasterTypeDemPath), 0);; IRasterDataset myRasterDataset = rasterWorkspace.OpenRasterDataset( System.IO.Path.GetFileName(MDParameters.rasterTypeDemPath)); IGeometricFunctionArguments geometricFunctionArguments = new GeometricFunctionArgumentsClass(); geometricFunctionArguments.DEM = myRasterDataset; ((IRasterTypeProperties)theRasterType).OrthorectificationParameters = geometricFunctionArguments; } #endregion #region Preparing Data Source Crawler Console.WriteLine("Preparing Data Source Crawler"); // Create a new property set to specify crawler properties. IPropertySet crawlerProps = new PropertySetClass(); // Specify a file filter crawlerProps.SetProperty("Filter", MDParameters.dataSourceFilter); // Specify whether to search subdirectories. crawlerProps.SetProperty("Recurse", true); // Specify the source path. crawlerProps.SetProperty("Source", MDParameters.dataSource); // Get the recommended crawler from the raster type based on the specified // properties using the IRasterBuilder interface. IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps); #endregion #region Add Rasters Console.WriteLine("Adding Rasters"); // Create a AddRaster parameters object. IAddRastersParameters AddRastersArgs = new AddRastersParametersClass(); // Specify the data crawler to be used to crawl the data. AddRastersArgs.Crawler = theCrawler; // Specify the raster type to be used to add the data. AddRastersArgs.RasterType = theRasterType; // Use the mosaic dataset operation interface to add // rasters to the mosaic dataset. theMosaicDatasetOperation.AddRasters(AddRastersArgs, null); #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges"); // Create a calculate cellsize ranges parameters object. ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass(); // Use the mosaic dataset operation interface to calculate cellsize ranges. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); #endregion #region Building Boundary Console.WriteLine("Building Boundary"); // Create a build boundary parameters object. IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass(); // Set flags that control boundary generation. boundaryArgs.AppendToExistingBoundary = true; // Use the mosaic dataset operation interface to build boundary. theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null); #endregion if (MDParameters.buildOverviews) { #region Defining Overviews Console.WriteLine("Defining Overviews"); // Create a define overview parameters object. IDefineOverviewsParameters defineOvArgs = new DefineOverviewsParametersClass(); // Use the overview tile parameters interface to specify the overview factor // used to generate overviews. ((IOverviewTileParameters)defineOvArgs).OverviewFactor = 3; // Use the mosaic dataset operation interface to define overviews. theMosaicDatasetOperation.DefineOverviews(defineOvArgs, null); #endregion #region Compute Pixel Size Ranges Console.WriteLine("Computing Pixel Size Ranges"); // Calculate cell size ranges to update the Min/Max pixel sizes. theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null); #endregion #region Generating Overviews Console.WriteLine("Generating Overviews"); // Create a generate overviews parameters object. IGenerateOverviewsParameters genPars = new GenerateOverviewsParametersClass(); // Set properties to control overview generation. IQueryFilter genQuery = new QueryFilterClass(); ((ISelectionParameters)genPars).QueryFilter = genQuery; genPars.GenerateMissingImages = true; genPars.GenerateStaleImages = true; // Use the mosaic dataset operation interface to generate overviews. theMosaicDatasetOperation.GenerateOverviews(genPars, null); #endregion } #region Report Console.WriteLine("Success."); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in CreateMD: " + exc.Message); Console.WriteLine("Shutting down."); #endregion } }
/// <summary> /// connect to ags server /// </summary> /// <param name="host">host</param> /// <returns>true if connected</returns> private static bool ConnectAGS(string host) { try { IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("url", host); propertySet.SetProperty("ConnectionMode", esriAGSConnectionMode.esriAGSConnectionModePublisher); propertySet.SetProperty("ServerType", esriAGSServerType.esriAGSServerTypeDiscovery); propertySet.SetProperty("user", username); propertySet.SetProperty("password", password); propertySet.SetProperty("ALLOWINSECURETOKENURL", true); IAGSServerConnectionName3 connectName = new AGSServerConnectionNameClass() as IAGSServerConnectionName3; connectName.ConnectionProperties = propertySet; IAGSServerConnectionAdmin agsAdmin = ((IName)connectName).Open() as IAGSServerConnectionAdmin; soAdmin = agsAdmin.ServerObjectAdmin; return true; } catch (Exception exc) { Console.WriteLine("Error: Couldn't connect to AGSServer: {0}. Message: {1}", host, exc.Message); return false; } }
static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } #endregion try { #region Setup MD Parameters MDParameters.gdbParentFolder = @"c:\temp\CreateMD"; // Choose which type of gdb to create/open. // 0 - Create File Gdb // 1 - Create Personal Gdb // 2 - Open SDE int gdbOption = 0; // Provide the proper extension based on the gdb you want to create. // e.g. MDParameters.gdbName = "samplePGdb.mdb" to create a personal gdb. // To use an SDE, set SDE connection properties below. MDParameters.gdbName = @"sampleGdb.gdb"; MDParameters.mosaicDatasetName = @"sampleMD"; // Specify the srs of the mosaic dataset ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); MDParameters.mosaicDatasetSrs = spatialrefFactory.CreateProjectedCoordinateSystem( (int)(esriSRProjCSType.esriSRProjCS_World_Mercator)); // 0 and PT_UNKNOWN for bits and bands = use defaults. MDParameters.mosaicDatasetBands = 0; MDParameters.mosaicDatasetBits = rstPixelType.PT_UNKNOWN; MDParameters.configKeyword = ""; // Product Definition key choices: // None // NATURAL_COLOR_RGB // NATURAL_COLOR_RGBI // FALSE_COLOR_IRG // FORMOSAT-2_4BANDS // GEOEYE-1_4BANDS // IKONOS_4BANDS // KOMPSAT-2_4BANDS // LANDSAT_6BANDS // LANDSAT_MSS_4BANDS // QUICKBIRD_4BANDS // RAPIDEYE_5BANDS // SPOT-5_4BANDS // WORLDVIEW-2_8BANDS // Setting this property ensures any data added to the MD with its // metadata defined gets added with the correct band combination. MDParameters.productDefinitionKey = "FALSE_COLOR_IRG"; MDParameters.rasterTypeName = "QuickBird"; // The next two properties can be left blank for defaults // The product filter defines which specific product of the raster // type to add, e.g. To specfiy Quickbird Basic use value "Basic" MDParameters.rasterTypeProductFilter = ""; // The product name specifies which template to use when adding data. // e.g. "Pansharpen and Multispectral" means both multispectral and // pansharpened rasters are added to the mosaic dataset. MDParameters.rasterTypeProductName = "Multispectral"; // Data source from which to read the data. MDParameters.dataSource = //@"\\Qalab_server\data\Raster\DOTNET\Input\DatasourcesRaster\FunctionRasterDataset\RasterDataset"; @"\\qalab_server\data\Raster\DOTNET\Input\DatasourcesRaster\MosaicDataset\QB\Torino"; //@"\\isdemo1\0_sampledata\SampleData\DataSets\QBBasic1b\Baghdad\X0388"; MDParameters.dataSourceFilter = @""; // No need to set if data source has an srs or if you want to use the MD srs as data source srs. MDParameters.dataSourceSrs = null; MDParameters.buildOverviews = true; #endregion MDParameters.emptyFgdbFolder = true; MDParameters.createFgdbParentFolder = false; #region Empty/Create Output Directory if (MDParameters.emptyFgdbFolder) { try { Console.WriteLine("Emptying Output Directory"); Directory.Delete(MDParameters.gdbParentFolder, true); Directory.CreateDirectory(MDParameters.gdbParentFolder); } catch (Exception) { } } if (MDParameters.createFgdbParentFolder && !System.IO.Directory.Exists(MDParameters.gdbParentFolder)) { Console.WriteLine("Creating Output Directory"); Directory.CreateDirectory(MDParameters.gdbParentFolder); } #endregion CreateMD createMD = new CreateMD(); if (gdbOption == 0) { #region Create MD in File GDB Console.WriteLine("Creating File GDB: " + MDParameters.gdbName); IWorkspace fgdbWorkspace = CreateFileGdbWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName); createMD.CreateMosaicDataset(fgdbWorkspace); #endregion } else if (gdbOption == 1) { #region Create MD in Personal GDB Console.WriteLine("Creating Personal GDB: " + MDParameters.gdbName); IWorkspace pGdbWorkspace = CreateAccessWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName); createMD.CreateMosaicDataset(pGdbWorkspace); #endregion } else if (gdbOption == 2) { #region Open SDE GDB // Set SDE connection properties. IPropertySet sdeProperties = new PropertySetClass(); sdeProperties.SetProperty("SERVER", "barbados"); sdeProperties.SetProperty("INSTANCE", "9411"); sdeProperties.SetProperty("VERSION", "sde.DEFAULT"); sdeProperties.SetProperty("USER", "gdb"); sdeProperties.SetProperty("PASSWORD", "gdb"); sdeProperties.SetProperty("DATABASE", "VTEST"); IWorkspace sdeWorkspace = CreateSdeWorkspace(sdeProperties); if (sdeWorkspace == null) { Console.WriteLine("Could not open SDE workspace: "); return; } #endregion #region Create MD in SDE MDParameters.mosaicDatasetName = @"sampleMD"; createMD.CreateMosaicDataset(sdeWorkspace); #endregion } #region Shutdown Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Shutting down."); #endregion #region Shutdown Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } }
/// <summary> /// Add WMS map service layer to map /// </summary> /// <param name="msi">Map service information</param> private void AddLayerWMS(esri.gpt.csw.MapServiceInfo msi, Boolean fromServerUrl) { if (msi == null) { throw new ArgumentNullException(); } try { string url = AppendQuestionOrAmpersandToUrlString(msi.Server); // append serviceParam to server url // todo: does msi.ServiceParam have a leading "?" or "&"? if (msi.ServiceParam.Length > 0 || !fromServerUrl) { url = url + msi.ServiceParam; url = AppendQuestionOrAmpersandToUrlString(url); } IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("URL", url); IMxDocument mxDoc = (IMxDocument)m_application.Document; IMap map = (IMap)mxDoc.FocusMap; IActiveView activeView = (IActiveView)map; IWMSGroupLayer wmsGroupLayer = (IWMSGroupLayer)new WMSMapLayerClass(); IWMSConnectionName wmsConnectionName = new WMSConnectionName(); wmsConnectionName.ConnectionProperties = propertySet; // connect to wms service IDataLayer dataLayer; bool connected = false; try { dataLayer = (IDataLayer)wmsGroupLayer; IName connName = (IName)wmsConnectionName; connected = dataLayer.Connect(connName); } catch (Exception ex) { ShowErrorMessageBox (StringResources.ConnectToMapServiceFailed + "\r\n" + ex.Message); connected = false; } if (!connected) return; // get service description out of the layer. the service description contains // inforamtion about the wms categories and layers supported by the service IWMSServiceDescription wmsServiceDesc = wmsGroupLayer.WMSServiceDescription; IWMSLayerDescription wmsLayerDesc; ILayer newLayer; ILayer layer; IWMSLayer newWmsLayer; IWMSGroupLayer newWmsGroupLayer; /* for (int i = 0; i < wmsServiceDesc.LayerDescriptionCount; i++) { newLayer = null; wmsLayerDesc = wmsServiceDesc.get_LayerDescription(i); if (wmsLayerDesc.LayerDescriptionCount == 0) { // wms layer newWmsLayer = wmsGroupLayer.CreateWMSLayer(wmsLayerDesc); newLayer = (ILayer)newWmsLayer; if (newLayer == null) { throw new Exception(StringResources.CreateWmsLayerFailed); }; } else { // wms group layer newWmsGroupLayer = wmsGroupLayer.CreateWMSGroupLayers(wmsLayerDesc); newLayer = (ILayer)newWmsGroupLayer; if (newLayer == null) { throw new Exception(StringResources.CreateWmsGroupLayerFailed); } } // add newly created layer // if(wmsGroupLayer.get_Layer(i).Name != newLayer.Name) wmsGroupLayer.InsertLayer(newLayer, 0); }*/ // configure the layer before adding it to the map layer = (ILayer)wmsGroupLayer; layer.Name = wmsServiceDesc.WMSTitle; ExpandLayer(layer, true); SetLayerVisibility(layer, true); // add to focus map map.AddLayer(layer); return; } catch (Exception ex) { ShowErrorMessageBox (StringResources.AddWmsLayerFailed + "\r\n" + ex.Message); } }
/// <summary> /// Create an array with the right BandName and Wavelength values for the corresponding key. /// </summary> /// <param name="key">Key to use.</param> /// <returns>Array with the correct BandName and Wavelength values.</returns> private static IArray SetBandProperties(string key) { IArray productDefProps = new ArrayClass(); IPropertySet band1Def = new PropertySetClass(); IPropertySet band2Def = new PropertySetClass(); IPropertySet band3Def = new PropertySetClass(); if (key == "NATURAL_COLOR_RGB" || key == "NATURAL_COLOR_RGBI") { band1Def.SetProperty("BandName", "Red"); band1Def.SetProperty("WavelengthMin", 630); band1Def.SetProperty("WavelengthMax", 690); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 530); band2Def.SetProperty("WavelengthMax", 570); band3Def.SetProperty("BandName", "Blue"); band3Def.SetProperty("WavelengthMin", 440); band3Def.SetProperty("WavelengthMax", 480); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); if (key == "NATURAL_COLOR_RGBI") { IPropertySet band4Def = new PropertySetClass(); band4Def.SetProperty("BandName", "NearInfrared"); band4Def.SetProperty("WavelengthMin", 770); band4Def.SetProperty("WavelengthMax", 830); productDefProps.Add(band4Def); } } else if (key == "FALSE_COLOR_IRG") { band1Def.SetProperty("BandName", "Infrared"); band1Def.SetProperty("WavelengthMin", 770); band1Def.SetProperty("WavelengthMax", 830); band2Def.SetProperty("BandName", "Red"); band2Def.SetProperty("WavelengthMin", 630); band2Def.SetProperty("WavelengthMax", 690); band3Def.SetProperty("BandName", "Green"); band3Def.SetProperty("WavelengthMin", 530); band3Def.SetProperty("WavelengthMax", 570); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); } else if (key == "FORMOSAT-2_4BANDS") { IPropertySet band4Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Blue"); band1Def.SetProperty("WavelengthMin", 450); band1Def.SetProperty("WavelengthMax", 520); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 520); band2Def.SetProperty("WavelengthMax", 600); band3Def.SetProperty("BandName", "Red"); band3Def.SetProperty("WavelengthMin", 630); band3Def.SetProperty("WavelengthMax", 690); band4Def.SetProperty("BandName", "NearInfrared"); band4Def.SetProperty("WavelengthMin", 760); band4Def.SetProperty("WavelengthMax", 900); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); } else if (key == "GEOEYE-1_4BANDS") { IPropertySet band4Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Blue"); band1Def.SetProperty("WavelengthMin", 450); band1Def.SetProperty("WavelengthMax", 510); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 510); band2Def.SetProperty("WavelengthMax", 580); band3Def.SetProperty("BandName", "Red"); band3Def.SetProperty("WavelengthMin", 655); band3Def.SetProperty("WavelengthMax", 690); band4Def.SetProperty("BandName", "NearInfrared"); band4Def.SetProperty("WavelengthMin", 780); band4Def.SetProperty("WavelengthMax", 920); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); } else if (key == "IKONOS_4BANDS") { IPropertySet band4Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Blue"); band1Def.SetProperty("WavelengthMin", 445); band1Def.SetProperty("WavelengthMax", 516); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 506); band2Def.SetProperty("WavelengthMax", 595); band3Def.SetProperty("BandName", "Red"); band3Def.SetProperty("WavelengthMin", 632); band3Def.SetProperty("WavelengthMax", 698); band4Def.SetProperty("BandName", "NearInfrared"); band4Def.SetProperty("WavelengthMin", 757); band4Def.SetProperty("WavelengthMax", 863); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); } else if (key == "KOMPSAT-2_4BANDS") { IPropertySet band4Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Blue"); band1Def.SetProperty("WavelengthMin", 450); band1Def.SetProperty("WavelengthMax", 520); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 520); band2Def.SetProperty("WavelengthMax", 600); band3Def.SetProperty("BandName", "Red"); band3Def.SetProperty("WavelengthMin", 630); band3Def.SetProperty("WavelengthMax", 690); band4Def.SetProperty("BandName", "NearInfrared"); band4Def.SetProperty("WavelengthMin", 760); band4Def.SetProperty("WavelengthMax", 900); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); } else if (key == "LANDSAT_6BANDS") { IPropertySet band4Def = new PropertySetClass(); IPropertySet band5Def = new PropertySetClass(); IPropertySet band6Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Blue"); band1Def.SetProperty("WavelengthMin", 450); band1Def.SetProperty("WavelengthMax", 520); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 520); band2Def.SetProperty("WavelengthMax", 600); band3Def.SetProperty("BandName", "Red"); band3Def.SetProperty("WavelengthMin", 630); band3Def.SetProperty("WavelengthMax", 690); band4Def.SetProperty("BandName", "NearInfrared_1"); band4Def.SetProperty("WavelengthMin", 760); band4Def.SetProperty("WavelengthMax", 900); band5Def.SetProperty("BandName", "NearInfrared_2"); band5Def.SetProperty("WavelengthMin", 1550); band5Def.SetProperty("WavelengthMax", 1750); band6Def.SetProperty("BandName", "MidInfrared"); band6Def.SetProperty("WavelengthMin", 2080); band6Def.SetProperty("WavelengthMax", 2350); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); productDefProps.Add(band5Def); productDefProps.Add(band6Def); } else if (key == "QUICKBIRD_4BANDS") { IPropertySet band4Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Blue"); band1Def.SetProperty("WavelengthMin", 450); band1Def.SetProperty("WavelengthMax", 520); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 520); band2Def.SetProperty("WavelengthMax", 600); band3Def.SetProperty("BandName", "Red"); band3Def.SetProperty("WavelengthMin", 630); band3Def.SetProperty("WavelengthMax", 690); band4Def.SetProperty("BandName", "NearInfrared"); band4Def.SetProperty("WavelengthMin", 760); band4Def.SetProperty("WavelengthMax", 900); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); } else if (key == "RAPIDEYE_5BANDS") { IPropertySet band4Def = new PropertySetClass(); IPropertySet band5Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Blue"); band1Def.SetProperty("WavelengthMin", 440); band1Def.SetProperty("WavelengthMax", 510); band2Def.SetProperty("BandName", "Green"); band2Def.SetProperty("WavelengthMin", 520); band2Def.SetProperty("WavelengthMax", 590); band3Def.SetProperty("BandName", "Red"); band3Def.SetProperty("WavelengthMin", 630); band3Def.SetProperty("WavelengthMax", 685); band4Def.SetProperty("BandName", "RedEdge"); band4Def.SetProperty("WavelengthMin", 690); band4Def.SetProperty("WavelengthMax", 730); band5Def.SetProperty("BandName", "NearInfrared"); band5Def.SetProperty("WavelengthMin", 760); band5Def.SetProperty("WavelengthMax", 850); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); productDefProps.Add(band5Def); } else if (key == "SPOT-5_4BANDS") { IPropertySet band4Def = new PropertySetClass(); band1Def.SetProperty("BandName", "Green"); band1Def.SetProperty("WavelengthMin", 500); band1Def.SetProperty("WavelengthMax", 590); band2Def.SetProperty("BandName", "Red"); band2Def.SetProperty("WavelengthMin", 610); band2Def.SetProperty("WavelengthMax", 680); band3Def.SetProperty("BandName", "NearInfrared"); band3Def.SetProperty("WavelengthMin", 780); band3Def.SetProperty("WavelengthMax", 890); band4Def.SetProperty("BandName", "ShortWaveInfrared"); band4Def.SetProperty("WavelengthMin", 1580); band4Def.SetProperty("WavelengthMax", 1750); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); } else if (key == "WORLDVIEW-2_8BANDS") { IPropertySet band4Def = new PropertySetClass(); IPropertySet band5Def = new PropertySetClass(); IPropertySet band6Def = new PropertySetClass(); IPropertySet band7Def = new PropertySetClass(); IPropertySet band8Def = new PropertySetClass(); band1Def.SetProperty("BandName", "CoastalBlue"); band1Def.SetProperty("WavelengthMin", 400); band1Def.SetProperty("WavelengthMax", 450); band2Def.SetProperty("BandName", "Blue"); band2Def.SetProperty("WavelengthMin", 450); band2Def.SetProperty("WavelengthMax", 510); band3Def.SetProperty("BandName", "Green"); band3Def.SetProperty("WavelengthMin", 510); band3Def.SetProperty("WavelengthMax", 580); band4Def.SetProperty("BandName", "Yellow"); band4Def.SetProperty("WavelengthMin", 585); band4Def.SetProperty("WavelengthMax", 625); band5Def.SetProperty("BandName", "Red"); band5Def.SetProperty("WavelengthMin", 630); band5Def.SetProperty("WavelengthMax", 690); band6Def.SetProperty("BandName", "RedEdge"); band6Def.SetProperty("WavelengthMin", 705); band6Def.SetProperty("WavelengthMax", 745); band7Def.SetProperty("BandName", "NearInfrared_1"); band7Def.SetProperty("WavelengthMin", 770); band7Def.SetProperty("WavelengthMax", 895); band8Def.SetProperty("BandName", "NearInfrared_2"); band8Def.SetProperty("WavelengthMin", 860); band8Def.SetProperty("WavelengthMax", 1040); productDefProps.Add(band1Def); productDefProps.Add(band2Def); productDefProps.Add(band3Def); productDefProps.Add(band4Def); productDefProps.Add(band5Def); productDefProps.Add(band6Def); productDefProps.Add(band7Def); productDefProps.Add(band8Def); } return(productDefProps); }
// Geocodes address by Address, City, State, ZIP code private IPoint GeocodeAddress(string strAddress, string strCity, string strState, string strCode) { if (m_objAddressGeocoding == null) throw new Exception("Cannot geocode address."); // Get Address fields from textboxes IPropertySet objAddressProperties = new PropertySetClass(); objAddressProperties.SetProperty("Street", strAddress); objAddressProperties.SetProperty("City", strCity); objAddressProperties.SetProperty("State", strState); objAddressProperties.SetProperty("ZIP", strCode); //// Match Address //IPropertySet objMatchProperties = null; //objMatchProperties = m_objAddressGeocoding.MatchAddress(objAddressProperties); //IFields objMatchFields = null; //objMatchFields = m_objAddressGeocoding.MatchFields; //if (objMatchFields.FieldCount > 0) //{ // // Use first candidate // IField objMatchField = null; // objMatchField = objMatchFields.get_Field(0); // if (objMatchField.Type == esriFieldType.esriFieldTypeGeometry) // return objMatchProperties.GetProperty(objMatchField.Name) as IPoint; //} // Match Address IPropertySet objMatchProperties = null; objMatchProperties = m_objAddressGeocoding.MatchAddress(objAddressProperties); IFields objMatchFields = null; objMatchFields = m_objAddressGeocoding.MatchFields; if (objMatchFields.FieldCount > 0) { // Use first candidate IField objGeometryField = null; int nFieldCount = objMatchFields.FieldCount; for (int nIndex = 0; nIndex < nFieldCount; nIndex++) { IField objCurField = objMatchFields.get_Field(nIndex); if (objCurField.Type == esriFieldType.esriFieldTypeGeometry) { objGeometryField = objCurField; break; } } if (objGeometryField != null) return objMatchProperties.GetProperty(objGeometryField.Name) as IPoint; else throw new Exception("Cannot obtain geometry field."); } throw new Exception("Cannot geocode address."); }
public void Init() { // Open workspace and feature class. IWorkspaceFactory wksf = new PostGisWorkspaceFactory(); //Open from zigFile //ws = wksf.OpenFromFile(@"C:\ziggis\ZigGis\example.zig", 0); //Open from PropertySet IPropertySet ps = new PropertySetClass(); ps.SetProperty("server", "localhost"); ps.SetProperty("database", "TUTORIAL"); ps.SetProperty("user", "psqluser"); ps.SetProperty("password", "psqluser"); ps.SetProperty("port", "5432"); ps.SetProperty("configfile", @"C:\ziggis\ZigGis\logging.config"); ws = wksf.Open(ps, 0); IFeatureWorkspace fwks = ws as IFeatureWorkspace; fc = fwks.OpenFeatureClass("zone"); // Create the new layer (default renderer is ISimpleRenderer) layer = new PostGisFeatureLayer(); layer.FeatureClass = fc; layer.Name = fc.AliasName; }
private IPropertySet method_3(bool bool_1, bool bool_2) { IPropertySet set; if (this.rdoAuthentic.SelectedIndex != 0) { string str2 = this.txtServer.Text.Trim(); string str3 = this.txtInstance.Text.Trim(); string str4 = this.txtDatabase.Text.Trim(); set = new PropertySetClass(); set.SetProperty("SERVER", str2); set.SetProperty("INSTANCE", str3); if (str4.Length >= 0) { set.SetProperty("DATABASE", str4); } switch (this.historicaltype_0) { case frmSDEConnectionDetialInfo.HISTORICALTYPE.VERSION: set.SetProperty("VERSION", this.lblVersion.Tag); break; case frmSDEConnectionDetialInfo.HISTORICALTYPE.HISTORICALTIMESTAMP: set.SetProperty("HISTORICAL_TIMESTAMP", this.lblVersion.Tag); break; case frmSDEConnectionDetialInfo.HISTORICALTYPE.HISTORICALNAME: set.SetProperty("HISTORICAL_NAME", this.lblVersion.Tag); break; } } else { set = new PropertySetClass(); string str = this.txtServer.Text.Trim(); set.SetProperty("SERVER", str); str = this.txtInstance.Text.Trim(); set.SetProperty("INSTANCE", str); str = this.txtDatabase.Text.Trim(); if (str.Length > 0) { set.SetProperty("DATABASE", str); } if (bool_1) { str = this.txtUser.Text.Trim(); set.SetProperty("USER", str); str = this.txtPassword.Text.Trim(); set.SetProperty("PASSWORD", str); } if (bool_2) { switch (this.historicaltype_0) { case frmSDEConnectionDetialInfo.HISTORICALTYPE.VERSION: set.SetProperty("VERSION", this.lblVersion.Tag); break; case frmSDEConnectionDetialInfo.HISTORICALTYPE.HISTORICALTIMESTAMP: set.SetProperty("HISTORICAL_TIMESTAMP", this.lblVersion.Tag); break; case frmSDEConnectionDetialInfo.HISTORICALTYPE.HISTORICALNAME: set.SetProperty("HISTORICAL_NAME", this.lblVersion.Tag); break; } } set.SetProperty("AUTHENTICATION_MODE", "DBMS"); return(set); } set.SetProperty("AUTHENTICATION_MODE", "OSA"); return(set); }
//////////////////////////////////////////////////////////////////////// // METHOD: CreateChildVersion private bool CreateChildVersion(ref IJTXJob pJob) { IVersion pNewVersion = null; try { string strVersionName = pJob.VersionName; int index = strVersionName.IndexOf(".", 0); if (index >= 0) { strVersionName = strVersionName.Substring(index + 1); } pJob.VersionName = strVersionName; pNewVersion = pJob.CreateVersion(esriVersionAccess.esriVersionAccessPublic); if (pNewVersion == null) { m_ipDatabase.LogMessage(3, 1000, "Unable to create version for child job ID: " + pJob.ID); } else { IPropertySet pOverrides = new PropertySetClass(); pOverrides.SetProperty("[VERSION]", pNewVersion.VersionName); JobUtilities.LogJobAction(m_ipDatabase, pJob, Constants.ACTTYPE_CREATE_VERSION, "", pOverrides); JTXUtilities.SendNotification(Constants.NOTIF_VERSION_CREATED, m_ipDatabase, pJob, pOverrides); } } catch (Exception ex) { m_ipDatabase.LogMessage(3, 1000, "Unable to create version for child job ID: " + pJob.ID + ". ERROR: " + ex.Message); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(pNewVersion); } return true; }
//根据文件路径打开文件 ygc 2012-8-29 private IWorkspace GetWorkspace(string filePath) { IWorkspace pWorkspace = null; string FileType = filePath.Substring(filePath.Length - 4, 4); switch (FileType) { case ".shp": IWorkspaceFactory pShpWorkSpaceFactory = new ShapefileWorkspaceFactory(); try { pWorkspace = pShpWorkSpaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(filePath), 0); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "错误"); return(null); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(pShpWorkSpaceFactory); } break; case ".mdb": IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("DATABASE", filePath); IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass(); try { pWorkspace = pWorkspaceFactory.Open(pPropertySet, 0); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "错误"); return(null); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspaceFactory); System.Runtime.InteropServices.Marshal.ReleaseComObject(pPropertySet); } break; case ".gdb": IWorkspaceFactory pGDBWorkSpace = new FileGDBWorkspaceFactoryClass(); try { pWorkspace = pGDBWorkSpace.OpenFromFile(filePath, 0); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "错误"); return(null); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(pGDBWorkSpace); } break; } return(pWorkspace); }
/// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="instance"></param> /// <param name="user"></param> /// <param name="password"></param> /// <param name="database"></param> /// <param name="version"></param> /// <param name="sdeFullPath">c:\\temp\\Sample.sde</param> /// <returns></returns> public IWorkspaceName CreateConnectionFile(string server, string instance, string user, string password, string database, string version, string sdeFullPath) { if (sdeFullPath == null) { } string sdePathWithSlash = ""; string sdeFileName = ""; string[] pathSplit = sdeFullPath.Split('\\'); sdePathWithSlash = pathSplit[0] + "\\\\" + pathSplit[1] + "\\\\"; sdeFileName = pathSplit[2]; MessageBox.Show("line 231 WspM "+sdePathWithSlash + "--" + sdeFileName); IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("SERVER", server); propertySet.SetProperty("INSTANCE", instance); propertySet.SetProperty("DATABASE", database); propertySet.SetProperty("USER", user); propertySet.SetProperty("PASSWORD", password); propertySet.SetProperty("VERSION", version); IWorkspaceFactory2 workspaceFactory = (IWorkspaceFactory2)new SdeWorkspaceFactoryClass(); return workspaceFactory.Create(sdePathWithSlash, sdeFileName, propertySet, 0); }
private void Load3DLayers2() { IWorkspace wsSource = GISOpr.getInstance().WorkSpace; // 为了在Skyline下预览数据, 必须取得数据库的连接信息 DBCore db = new DBCore(true); IList paramList = db.GetAll(typeof(Tbsysparams), "Paramid"); IPropertySet workspaceProperySet = new PropertySetClass(); foreach (Tbsysparams param in paramList) { if (param.Paramenname.ToUpper() == "SDESERVER") { workspaceProperySet.SetProperty("Server", param.Paramvalue); } if (param.Paramenname.ToUpper() == "SDEINSTANCE") { workspaceProperySet.SetProperty("Instance", param.Paramvalue); } if (param.Paramenname.ToUpper() == "SDEVERSION") { workspaceProperySet.SetProperty("Version", param.Paramvalue); } if (param.Paramenname.ToUpper() == "SDEUSER") { workspaceProperySet.SetProperty("User", param.Paramvalue); } if (param.Paramenname.ToUpper() == "SDEPASSWORD") { workspaceProperySet.SetProperty("Password", param.Paramvalue); } } IWorkspaceCatalogItem itemWorkspace = new WorkspaceCatalogItem(workspaceProperySet, Hy.Catalog.Utility.enumWorkspaceType.SDE, null, "当前空间数据库"); if ((wsSource as IWorkspace2).get_NameExists(esriDatasetType.esriDTTable, "ThreeDimenLayersCache")) { IFeatureWorkspace fwsSource = (wsSource as IFeatureWorkspace); ITable t3DLayers = fwsSource.OpenTable("ThreeDimenLayersCache"); ICursor cursor = t3DLayers.Search(null, true); IRow rowLayer = cursor.NextRow(); int fNameIndex = cursor.FindField("LayerName"); int fTypeIndex = cursor.FindField("LayerType"); int f3DType = (int)enumCatalogType.FeatureClass3D; while (rowLayer != null) { if (f3DType == Convert.ToInt32(rowLayer.get_Value(fTypeIndex))) { IFeatureClass fClass3D = fwsSource.OpenFeatureClass(rowLayer.get_Value(fNameIndex) as string); // ICatalogItem curItem = new FeatureClassCatalogItem((fClass3D as IDataset).FullName as IDatasetName, null); curItem.WorkspaceItem = itemWorkspace; TreeNode node3D = this.m_Node3D.Nodes.Add(curItem.Name); node3D.ImageIndex = 19; node3D.SelectedImageIndex = 19; node3D.Tag = curItem; } rowLayer = cursor.NextRow(); } } else { // ParentName和Desription(以及LayerType)都保留,到支持栅格数据时可能用得到 string strSQL = @"Create Table ThreeDimenLayersCache( LayerName varchar2(256) not null, ParentName varchar2(256) , Description varchar(4000), LayerType INTEGER default " + ((int)enumCatalogType.FeatureClass3D).ToString() + ")"; wsSource.ExecuteSQL(strSQL); IEnumDatasetName enDatasetName = wsSource.get_DatasetNames(esriDatasetType.esriDTFeatureClass); IDatasetName dsName3D = enDatasetName.Next(); while (dsName3D != null) { if ((dsName3D as IFeatureClass).ShapeType == esriGeometryType.esriGeometryMultiPatch) { // 存入数据库缓存并加载到树上 strSQL = string.Format("Insert into ThreeDimenLayersCache(LayerName) values('{0}')", dsName3D.Name); wsSource.ExecuteSQL(strSQL); // ICatalogItem curItem = new FeatureClassCatalogItem(dsName3D, null); curItem.WorkspaceItem = itemWorkspace; TreeNode node3D = this.m_Node3D.Nodes.Add(curItem.Name); node3D.ImageIndex = 19; node3D.SelectedImageIndex = 19; node3D.Tag = curItem; } dsName3D = enDatasetName.Next(); } // FeatureDataset底下的3维FeatureClass enDatasetName = wsSource.get_DatasetNames(esriDatasetType.esriDTFeatureDataset); IDatasetName dsNameContainer = enDatasetName.Next(); while (dsNameContainer != null) { IEnumDatasetName enDsName3D = dsNameContainer.SubsetNames; dsName3D = enDsName3D.Next(); while (dsName3D != null) { if (dsName3D is IFeatureClass && (dsName3D as IFeatureClass).ShapeType == esriGeometryType.esriGeometryMultiPatch) { // 存入数据库缓存并加载到树上 strSQL = string.Format("Insert into ThreeDimenLayersCache(LayerName) values('{0}')", dsName3D.Name); wsSource.ExecuteSQL(strSQL); // ICatalogItem curItem = new FeatureClassCatalogItem(dsName3D, null); curItem.WorkspaceItem = itemWorkspace; TreeNode node3D = this.m_Node3D.Nodes.Add(curItem.Name); node3D.ImageIndex = 19; node3D.SelectedImageIndex = 19; node3D.Tag = curItem; } dsName3D = enDsName3D.Next(); } dsNameContainer = enDatasetName.Next(); } } m_Node3D.Expand(); }
/// <summary> /// tạo file connection *.sde /// </summary> /// <param name="server"></param> /// <param name="instance"></param> /// <param name="user"></param> /// <param name="password"></param> /// <param name="database"></param> /// <param name="version"></param> /// <param name="sdePathWithSlash">c:\\temp\\</param> /// <param name="sdeFileName">Sample.sde</param> /// <returns></returns> public IWorkspaceName CreateConnectionFile(string server, string instance, string user, string password, string database, string version,string sdePathWithSlash,string sdeFileName) { IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("SERVER", server); propertySet.SetProperty("INSTANCE", instance); propertySet.SetProperty("DATABASE", database); propertySet.SetProperty("USER", user); propertySet.SetProperty("PASSWORD", password); propertySet.SetProperty("VERSION", version); IWorkspaceFactory2 workspaceFactory = (IWorkspaceFactory2)new SdeWorkspaceFactoryClass(); return workspaceFactory.Create(sdePathWithSlash, sdeFileName, propertySet, 0); }
/// <summary> /// Adds ArcGIS layer to map /// </summary> /// <param name="ipMxDoc"></param> /// <param name="strServer"></param> /// <param name="strLayerName"></param> /// <param name="strSecretName"></param> /// <returns></returns> private bool addLayerAGS(IMxDocument ipMxDoc, string strServer, string strLayerName, string strSecretName) { IPropertySet2 pProps = null; string pServerUrl; string strServerObj; pServerUrl = GetAGSServiceUrl(strServer); // connect to the GIS server IAGSServerConnectionFactory pAGSServerConnectionFactory = new AGSServerConnectionFactory(); pProps = (IPropertySet2) new PropertySet(); pProps.SetProperty("URL", pServerUrl); IAGSServerConnection pAGSConnection = pAGSServerConnectionFactory.Open(pProps, 0); //get server objectname from url strServerObj = GetServerObjectName(strServer); // enumerate over server objects IAGSEnumServerObjectName pAGSSObjs = pAGSConnection.ServerObjectNames; IAGSServerObjectName pAGSSObj = pAGSSObjs.Next(); while (pAGSSObj != null) { if (pAGSSObj.Type == "MapServer" && pAGSSObj.Name == strServerObj) { break; } pAGSSObj = pAGSSObjs.Next(); } IName pName = (IName)pAGSSObj; IAGSServerObject pAGSO = (IAGSServerObject)pName.Open(); IMapServer mapServer = (IMapServer)pAGSO; IPropertySet prop = new PropertySetClass(); prop.SetProperty("URL", pServerUrl); prop.SetProperty("Name", pAGSSObj.Name); //Create new layer IMapServerLayer pMSLayer = (IMapServerLayer) new MapServerLayer(); pMSLayer.ServerConnect(pAGSSObj, mapServer.DefaultMapName); if (!isMapServerAdded(strServer)) { setAGSLayerVisiblity((MapServerLayer)pMSLayer, strSecretName); IMap ipMap = ipMxDoc.FocusMap; ipMap.AddLayer((ILayer)pMSLayer); logger.writeLog(StringResources.AddAGSLayer + strSecretName); } else { // set visibility setAGSLayerVisiblity((MapServerLayer)pMSLayer, strSecretName); } //add to the service list string strItem = EncodeServiceList(strServer, strLayerName, strSecretName); // m_pLogger.Msg "adding to service list : " & strItem colServiceList.Add(strItem); //set flag logger.writeLog("strServer = " + strServer + " strServer & strLayerName = " + strServer + strLayerName); return(true); }