//-------------------------------------------------------------------------------- public static IWorkspace GetSDEWorkspace() { try { //声明临时路径 string path = @"d:\temp"; // 声明临时.sde文件名称 string sdeName = @"localhost.sde"; string sdePath = path + "\\" + sdeName; // 如果已经存在了,则删除了重新创建 if (File.Exists(sdePath)) { File.Delete(sdePath); } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory"); IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass(); // 创建.sde文件 IWorkspaceName workspaceName = workspaceFactory.Create(path, sdeName, ConnectSDE(true), 0); // 使用.sde文件,通过.sde文件获取IWorkspace,之后就可以对数据库中的数据进行操作了 IWorkspace pWorkspace = workspaceFactory.OpenFromFile(sdePath, 0); return(pWorkspace); } catch (Exception ex) { return(null); } }
public static IWorkspace GetWorkspace(string datasource, DataSourceType datasourceType) { switch (datasourceType) { case DataSourceType.SdeFilePath: { SdeWorkspaceFactory sdeWf = new SdeWorkspaceFactoryClass(); return(sdeWf.OpenFromFile(datasource, 0)); } case DataSourceType.SdeTxt: throw new NotImplementedException(); case DataSourceType.SdeJson: throw new NotImplementedException(); case DataSourceType.GdbFilePath: { FileGDBWorkspaceFactory fileWf = new FileGDBWorkspaceFactoryClass(); return(fileWf.OpenFromFile(datasource, 0)); } case DataSourceType.ShapefilePath: throw new NotImplementedException(); default: return(null); break; } }
// // CONSTRUCTOR // public SdeValidator(string sde) : base() { this._sdeFile = sde; IWorkspaceFactory2 workspaceFactory = new SdeWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(this._sdeFile = sde, 0); base.SetWorkspace(workspace); }
/// <summary> /// Converts string to Workspace /// </summary> /// <param name="s">The connection string for geodatabase</param> /// <returns>geodatabase IWorkspace </returns> public static IWorkspace ToWorkspace(this string s) { IWorkspace workspace = null; try { if (s.EndsWith("sde", StringComparison.CurrentCultureIgnoreCase)) { IWorkspaceFactory factory = new SdeWorkspaceFactoryClass(); workspace = factory.OpenFromFile(s, 0); } else if (s.EndsWith("gdb", StringComparison.CurrentCultureIgnoreCase)) { IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass(); workspace = factory.OpenFromFile(s, 0); } else if (s.EndsWith("mdb", StringComparison.CurrentCultureIgnoreCase)) { IWorkspaceFactory factory = new AccessWorkspaceFactoryClass(); workspace = factory.OpenFromFile(s, 0); } } catch (Exception e) { Trace.WriteLine(e.StackTrace); Console.WriteLine(e.Message); } return(workspace); }
public static IFeatureClass GetFeatureClass(string datasource, DataSourceType dataSourceType, string featureClassName) { IWorkspace workspace = null; switch (dataSourceType) { case DataSourceType.SdeFilePath: { SdeWorkspaceFactory sdeWorkspaceFactory = new SdeWorkspaceFactoryClass(); workspace = sdeWorkspaceFactory.OpenFromFile(datasource, 1); } break; case DataSourceType.SdeTxt: throw new NotImplementedException(); break; case DataSourceType.SdeJson: throw new NotImplementedException(); break; case DataSourceType.GdbFilePath: { FileGDBWorkspaceFactory fileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); workspace = fileGDBWorkspaceFactory.OpenFromFile(datasource, 1); } //throw new NotImplementedException(); break; case DataSourceType.ShapefilePath: throw new NotImplementedException(); break; default: break; } var featureWorkspace = (IFeatureWorkspace)workspace; IFeatureClass tryOpenFeatureClass; try { tryOpenFeatureClass = featureWorkspace.OpenFeatureClass(featureClassName); } catch (Exception ex) { throw ex; } //((IFeatureWorkspace)workspace).CreateFeatureClass() return(featureWorkspace.OpenFeatureClass(featureClassName)); }
} // getFCNames public void doWork() { Log.p("doWork started..."); String sdeconnfname = mSdeConnFileName; // "c:\\t\\test.sde"; String tabnames = mTabName; // "T.TAB1,T.TAB2"; Log.p("Open the source gdb"); IWorkspaceFactory wspFact = new SdeWorkspaceFactoryClass(); IWorkspace wsp = wspFact.OpenFromFile(sdeconnfname, 0); Log.p("Get FC names"); IEnumNameEdit edtNames = getFCNames(wsp, tabnames); IEnumName names = (IEnumName)edtNames; Log.p("Create a scratch workspace factory"); IScratchWorkspaceFactory scrWspFact = new ScratchWorkspaceFactoryClass(); IWorkspace scrWsp = scrWspFact.CreateNewScratchWorkspace(); IDataset dset = (IDataset)scrWsp; IName scrWspName = dset.FullName; Log.p("Create a Transfer object and a name mapping"); IGeoDBDataTransfer trans = new GeoDBDataTransferClass(); IEnumNameMapping nameMaps = null; Boolean hasConflicts = trans.GenerateNameMapping( names, scrWspName, out nameMaps); if (hasConflicts) { throw new ArgumentException("Name mapping has conflicts."); } bool expData = mNeedData; string fname = mExpFileName; bool getMeta = mNeedMeta; bool compressed = false; bool binaryGeom = true; IGdbXmlExport exp = new GdbExporterClass(); if (expData == false) { Log.p(String.Format("Export schema (u need sdeexport for data); file [{0}], metadata [{1}]", fname, getMeta)); exp.ExportDatasetsSchema(nameMaps, fname, compressed, getMeta); } else { Log.p(String.Format("Export schema&data; file [{0}], metadata [{1}]", fname, getMeta)); exp.ExportDatasets(nameMaps, fname, binaryGeom, compressed, getMeta); } Log.p("OK, xml writed.", "both"); } // method doWork
public static IWorkspace OpenFissureWorkspace() { string connectionFile = @"C:\Users\username\AppData\Roaming\ESRI\Desktop10.2\ArcCatalog\EarthFissures.sde"; // Read in the database connection properties from config.txt //string[] lines = System.IO.File.ReadAllLines(@"../../config.txt"); string path = @"C:\tmp\config.txt"; string cfg = ""; if (File.Exists(path)) { try { string[] lines = System.IO.File.ReadAllLines(path); Dictionary <string, string> dbConn = new Dictionary <string, string>(); foreach (string line in lines) { dbConn.Add(line.Split('=')[0], line.Split('=')[1]); cfg = cfg + " \n " + line; } if (dbConn["dbfile"].Length > 0) { connectionFile = dbConn["dbfile"]; IWorkspaceFactory wsFact2 = new SdeWorkspaceFactoryClass(); return(wsFact2.OpenFromFile(connectionFile, 0)); } else { IWorkspaceFactory wsFact = new SdeWorkspaceFactoryClass(); IPropertySet connectionProperties = new PropertySetClass(); connectionProperties.SetProperty("SERVER", dbConn["server"]); connectionProperties.SetProperty("INSTANCE", dbConn["instance"]); connectionProperties.SetProperty("DATABASE", dbConn["database"]); connectionProperties.SetProperty("AUTHENTICATION_MODE", dbConn["authentication_mode"]); connectionProperties.SetProperty("VERSION", dbConn["version"]); return(wsFact.Open(connectionProperties, 0)); } } catch (Exception ex) { MessageBox.Show("Cannot Connect to Fissure Database - Check your config.txt file " + cfg); return(null); } } else { return(null); } }
/// <summary> /// 获取SDE数据库工作空间 /// </summary> /// <param name="sdePath">.sde文件</param> /// <returns></returns> public static ZWorkspace GetSdeWorkspace(string sdePath) { if (sdePath == "" || !sdePath.EndsWith(".sde") || !File.Exists(sdePath)) { throw new Exception(string.Format("请选择sde文件")); } try { IWorkspaceFactory2 wf = new SdeWorkspaceFactoryClass() as IWorkspaceFactory2; IWorkspace workspace = wf.OpenFromFile(sdePath, 0); return(new ZWorkspace(workspace)); } catch (Exception ex) { throw new Exception(string.Format("打开SDE数据库失败"), ex); } }
private void UpdateDBConnection(string msdFilepath, string sde) { IWorkspaceFactory2 wf = new SdeWorkspaceFactoryClass(); IWorkspace ws = wf.OpenFromFile(sde, 0); IDataset ds = (IDataset)ws; IWorkspaceName2 wn = (IWorkspaceName2)ds.FullName; string conn = wn.ConnectionString; IMSDHelper helper = new MSDHelper(); helper.Open(msdFilepath); var maps = helper.GetMaps(); for (var i = 0; i < maps.Count; i++) { var layers = helper.GetLayers(maps.Element[i]); for (var j = 0; j < layers.Count; j++) { helper.PutWorkspaceConnectionStringInLayer(layers.Element[i], conn, false); } } }
private void printSDEConnections(string sde) { try { // We use IWorkspacename2 so that it returns a ENCRYPTED_PASSWORD required // for the connection string in an MSD. IWorkspaceFactory2 wf = new SdeWorkspaceFactoryClass(); IWorkspace ws = wf.OpenFromFile(txtSDE.Text, 0); IDataset ds = (IDataset)ws; IWorkspaceName2 wn = (IWorkspaceName2)ds.FullName; List <string> dbconns = wn.ConnectionString.Split(';').ToList <string>(); foreach (string param in dbconns) { this.richTextBox2.Text += param + "\n"; } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void doWork() { String sdeconnfname = mSdeConnFileName; // "c:\\t\\test.sde"; String tabname = mTabName; // "TEST.TABLE1"; Log.p("doWork started..."); IWorkspaceFactory wspf = new SdeWorkspaceFactoryClass(); Log.p("open worksp. from sde conn.file [" + sdeconnfname + "]"); IWorkspace wsp = wspf.OpenFromFile(sdeconnfname, 0); IFeatureWorkspaceManage fwspm = (IFeatureWorkspaceManage)wsp; Boolean isreg = fwspm.IsRegisteredAsObjectClass(tabname); if (isreg != false) { Log.p("registered already, tab.name [" + tabname + "]", "both"); // throw (new Exception("registered already, tab.name [" + tabname + "]")); return; } IFeatureWorkspace fwsp = (IFeatureWorkspace)wsp; Log.p("open tab. by name [" + tabname + "]", "both"); ITable tbl = fwsp.OpenTable(tabname); // IObjectClass from ITable // IClassSchemaEdit from objectClass // ISchemaLock from objectClass // schemaLock.ChangeSchemaLock() // schemaEdit.RegisterAsObjectClass() // schemaLock.ChangeSchemaLock() IObjectClass oc = (IObjectClass)tbl; Log.p("do register..."); RegisterWithGeodatabase(oc, mOidFldName); Log.p("OK, registered.", "both"); } // doWork method
public static void ExportDatabase(IWorkspace theWorkspace) { // Try and make sure the user understands what they're doing MessageBox.Show("You must first browse to a previously generated, empty geodatabase.", "NCGMP Tools"); // Browse for a file, personal or SDE geodatabase IWorkspaceFactory wsFact = null; IWorkspace openedWorkspace = null; IGxObjectFilter objectFilter = new GxFilterWorkspaces(); IGxObject openedObject = commonFunctions.OpenArcFile(objectFilter, "Please select an empty database"); if (openedObject == null) { return; } // Check to see if it is a File, Personal or SDE database, create appropriate workspace factory string pathToOpen = null; switch (openedObject.Category) { case "Personal Geodatabase": wsFact = new AccessWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "File Geodatabase": wsFact = new FileGDBWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "Spatial Database Connection": wsFact = new SdeWorkspaceFactoryClass(); IGxRemoteDatabaseFolder remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent; pathToOpen = remoteDatabaseFolder.Path + openedObject.Name; break; default: break; } openedWorkspace = wsFact.OpenFromFile(pathToOpen, 0); // Okay, now export the current database to an XML doc string tempFilePath = System.IO.Path.GetTempFileName(); tempFilePath += ".xml"; IGdbXmlExport xmlExporter = new GdbExporterClass(); xmlExporter.ExportWorkspace(theWorkspace, tempFilePath, true, false, false); // Import to the new database // Use the temp file to perform the import IGdbXmlImport xmlImporter = new GdbImporterClass(); IEnumNameMapping enumNameMapping = null; bool conflictsFound = xmlImporter.GenerateNameMapping(tempFilePath, openedWorkspace, out enumNameMapping); try { // Deal with conflicts (lifted wholesale from http://help.arcgis.com/en/sdk/10.0/arcobjects_net/conceptualhelp/index.html#/d/00010000011m000000.htm) if (conflictsFound) { IName workspaceName = ((IDataset)openedWorkspace).FullName; // Iterate through each name mapping. INameMapping nameMapping = null; enumNameMapping.Reset(); while ((nameMapping = enumNameMapping.Next()) != null) { // Resolve the mapping's conflict (if there is one). if (nameMapping.NameConflicts) { nameMapping.TargetName = nameMapping.GetSuggestedName(workspaceName); } // See if the mapping's children have conflicts. IEnumNameMapping childEnumNameMapping = nameMapping.Children; if (childEnumNameMapping != null) { childEnumNameMapping.Reset(); // Iterate through each child mapping. INameMapping childNameMapping = null; while ((childNameMapping = childEnumNameMapping.Next()) != null) { if (childNameMapping.NameConflicts) { childNameMapping.TargetName = nameMapping.GetSuggestedName (workspaceName); } } } } } // Perform the import xmlImporter.ImportWorkspace(tempFilePath, enumNameMapping, openedWorkspace, false); } catch (Exception ex) { MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine + "XML Workspace Doc written to: " + tempFilePath); } // Perhaps, strip the SysInfo table }
static void Main(string[] args) { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeEngine, esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB }, new esriLicenseExtensionCode[] { }); //ESRI License Initializer generated code. IWorkspaceFactory2 wsf2 = new SdeWorkspaceFactoryClass() as IWorkspaceFactory2; IWorkspace ws = wsf2.OpenFromFile(@"C:\Users\User123\AppData\Roaming\ESRI\Desktop10.1\ArcCatalog\ConnectionToSQLServer.sde", 0); IFeatureWorkspace fws = ws as IFeatureWorkspace; ESRI.ArcGIS.Geodatabase.IFeatureClass fc = fws.OpenFeatureClass("DB_101.DBO.Points_Projected_UTMz11NCopy4_3"); ITableWrite tw = fc as ITableWrite; int numRows = 300; Int32[] int32Array = new Int32[numRows]; for (Int32 i = 0; i < numRows; i++) { int32Array[i] = i; } IGeoDatabaseBridge2 gdbBridge2 = new GeoDatabaseHelperClass(); //IGeoDatabaseBridge2 fc_gdbBridge2 = fc as IGeoDatabaseBridge2; bool Recycling = false; IFeatureCursor featCursor = gdbBridge2.GetFeatures(fc, ref int32Array, Recycling); ISet setOfRows = new SetClass(); IFeature feat; feat = featCursor.NextFeature(); while (feat != null) { IObject obj = feat as IObject; setOfRows.Add(obj); feat = featCursor.NextFeature(); } // TEST 1: ITableWrite.DeleteRows //------------------------------- DateTime dateTimeNow_Start = System.DateTime.Now; tw.DeleteRows(setOfRows); DateTime dateTimeNow_End = System.DateTime.Now; Double timeDifference = dateTimeNow_End.Subtract(dateTimeNow_Start).Milliseconds; System.Diagnostics.Debug.WriteLine("ITableWrite.DeleteRows(" + numRows + "rows): Processing time = " + timeDifference + " Milliseconds."); // TEST 2: ITableWrite.RemoveRows //------------------------------- //DateTime dateTimeNow_Start = System.DateTime.Now; //tw.RemoveRows(setOfRows); //DateTime dateTimeNow_End = System.DateTime.Now; //Double timeDifference = dateTimeNow_End.Subtract(dateTimeNow_Start).Milliseconds; //System.Diagnostics.Debug.WriteLine("ITableWrite.RemoveRows(" + numRows + "rows): Processing time = " + // timeDifference + " Milliseconds."); //Do not make any call to ArcObjects after ShutDownApplication() m_AOLicenseInitializer.ShutdownApplication(); }
protected override void OnClick() { // string getSqlDatabase = "False"; findDatabase: // Check the registry // Find a Database IWorkspaceFactory wsFact = null; IWorkspace openedWorkspace = null; // Browse for a file, personal or SDE geodatabase IGxObjectFilter objectFilter = new GxFilterWorkspaces(); IGxObject openedObject = commonFunctions.OpenArcFile(objectFilter, "Please select an NCGMP database"); if (openedObject == null) { return; } // Check to see if it is a File, Personal or SDE database, create appropriate workspace factory string pathToOpen = null; switch (openedObject.Category) { case "Personal Geodatabase": wsFact = new AccessWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "File Geodatabase": wsFact = new FileGDBWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "Spatial Database Connection": wsFact = new SdeWorkspaceFactoryClass(); IGxRemoteDatabaseFolder remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent; pathToOpen = remoteDatabaseFolder.Path + "\\" + openedObject.Name; break; default: break; } try { openedWorkspace = wsFact.OpenFromFile(pathToOpen, 0); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } // Check to see if the database is valid NCGMP bool isValid = ncgmpChecks.IsWorkspaceMinNCGMPCompliant(openedWorkspace); if (isValid == false) { MessageBox.Show("The selected database is not a valid NCGMP database.", "NCGMP Toolbar"); goto findDatabase; } else { isValid = ncgmpChecks.IsSysInfoPresent(openedWorkspace); if (isValid == false) { MessageBox.Show("In order to use these tools, the NCGMP database must contain a SysInfo table.", "NCGMP Toolbar"); goto findDatabase; } } bool isTopologyUsed = ncgmpChecks.IsTopologyUsed(openedWorkspace); bool hasStationTables = ncgmpChecks.IsAzgsStationAddinPresent(openedWorkspace); bool hasStandardLithtables = ncgmpChecks.IsStandardLithAddinPresent(openedWorkspace); bool hasRepresentations = ncgmpChecks.AreRepresentationsUsed(openedWorkspace); // Add FeatureClasses and tables to the ArcMap Project AddLayersToMap(openedWorkspace, isTopologyUsed, hasStationTables, hasRepresentations); // Populate the Data Sources combobox }
/// <summary> /// Connect to an enterprise geodatabase using an sde connection file. /// </summary> /// <param name="connectionFile">The sde file containing the connection parameters</param> /// <returns>the workspace interface for the connected datase</returns> public static IWorkspace ConnectWithFile(string connectionFile) { IWorkspaceFactory pWkspFact = new SdeWorkspaceFactoryClass(); return(pWkspFact.OpenFromFile(connectionFile, 0)); }
public static IWorkspace ArcSdeWorkspaceFromFile(String connectionFile) { IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass(); return(workspaceFactory.OpenFromFile(connectionFile, 0)); }
//-------------------------------------------------------------------------------- public static IWorkspace GetSDEWorkspace() { try { //声明临时路径 string path = @"d:\temp"; // 声明临时.sde文件名称 string sdeName = @"localhost.sde"; string sdePath = path + "\\" + sdeName; // 如果已经存在了,则删除了重新创建 if (File.Exists(sdePath)) { File.Delete(sdePath); } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory"); IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass(); // 创建.sde文件 IWorkspaceName workspaceName = workspaceFactory.Create(path, sdeName, ConnectSDE(true), 0); // 使用.sde文件,通过.sde文件获取IWorkspace,之后就可以对数据库中的数据进行操作了 IWorkspace pWorkspace = workspaceFactory.OpenFromFile(sdePath, 0); return pWorkspace; } catch (Exception ex) { return null; } }
public static List<string> GetAllExpressDesigns() { ICursor cur = null; ICursor cur2 = null; ICursor cur3 = null; List<string> designNames = new List<string>(); List<DesignFeature> designFeatures = new List<DesignFeature>(); HashSet<int> expressFeatureDesignsIds = new HashSet<int>(); try { IWorkspaceFactory wsf = new SdeWorkspaceFactoryClass(); var ws = wsf.OpenFromFile(Common.GetConfiguration("SDEConnectionFile"), 0); _fws = ws as IFeatureWorkspace; IFeatureWorkspaceManage2 fwsm2 = (IFeatureWorkspaceManage2)_fws; Workspace = fwsm2; var qd = _fws.CreateQueryDef(); qd.Tables = "schneiderville.sde.mm_express_features"; cur = qd.Evaluate(); IRow r = cur.NextRow(); Dictionary<int, string> IdToClassName = new Dictionary<int, string>(); while (r != null) { DesignFeature df = new DesignFeature(); df.ExpressFeatureDesignID = Convert.ToInt32( r.get_Value(r.Fields.FindField("DESIGNID"))); df.FeatureOID = Convert.ToInt32(r.get_Value(r.Fields.FindField("FEATUREOID"))); df.FeatureClassID = Convert.ToInt32(r.get_Value(r.Fields.FindField("FEATURECLASSID"))); if (IdToClassName.ContainsKey(df.FeatureClassID) == false) { string className = fwsm2.GetObjectClassNameByID(df.FeatureClassID); IdToClassName.Add(df.FeatureClassID, className); } designFeatures.Add(df); if (expressFeatureDesignsIds.Contains(df.ExpressFeatureDesignID) == false) { expressFeatureDesignsIds.Add(df.ExpressFeatureDesignID); var qd2 = _fws.CreateQueryDef(); qd2.Tables = "schneiderville.SDE.mm_express_designs"; qd2.WhereClause = "OBJECTID = " + df.ExpressFeatureDesignID; qd2.SubFields= "OBJECTID,DESIGNID"; cur2 = qd2.Evaluate(); IRow r2 = cur2.NextRow(); if (r2 != null) { int wmsDesignOID = Convert.ToInt32(r2.get_Value(r2.Fields.FindField("DESIGNID"))); var qd3 = _fws.CreateQueryDef(); qd3.Tables = "schneiderville.process.mm_wms_design"; qd3.WhereClause = "ID = " + wmsDesignOID; qd3.SubFields = "ID,NAME"; cur3 = qd3.Evaluate(); IRow r3 = cur3.NextRow(); if (r3 != null) { string designName = r3.get_Value(r3.Fields.FindField("NAME")).ToString(); designNames.Add(designName + " (" + df.ExpressFeatureDesignID + ")"); //Express Design ID in parentheses } } try { Marshal.FinalReleaseComObject(cur2); Marshal.FinalReleaseComObject(cur3); } catch { } } r = cur.NextRow(); } GetNameByID = IdToClassName; _designFeatures = designFeatures; return designNames; } finally { Marshal.FinalReleaseComObject(cur); } }
private void tlsbtnShowCopyPanel_Click(object sender, EventArgs e) { #region "Open the Database to Copy From" findDatabase: // Check the registry string regValue = commonFunctions.ReadReg("Software\\NCGMPTools", "getSqlDatabase"); // Find a Database IWorkspaceFactory wsFact = null; IWorkspace openedWorkspace = null; // Browse for a file, personal or SDE geodatabase IGxObjectFilter objectFilter = new GxFilterWorkspaces(); IGxObject openedObject = commonFunctions.OpenArcFile(objectFilter, "Please select an NCGMP database"); if (openedObject == null) { return; } // Check to see if it is a File, Personal or SDE database, create appropriate workspace factory string pathToOpen = null; switch (openedObject.Category) { case "Personal Geodatabase": wsFact = new AccessWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "File Geodatabase": wsFact = new FileGDBWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "Spatial Database Connection": case "Database Connection": wsFact = new SdeWorkspaceFactoryClass(); IGxRemoteDatabaseFolder remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent; pathToOpen = remoteDatabaseFolder.Path + openedObject.Name; break; default: break; } openedWorkspace = wsFact.OpenFromFile(pathToOpen, 0); // Check to see if the database is valid NCGMP bool isValid = ncgmpChecks.IsWorkspaceMinNCGMPCompliant(openedWorkspace); if (isValid == false) { MessageBox.Show("The selected database is not a valid NCGMP database.", "NCGMP Toolbar"); goto findDatabase; } //else //{ // isValid = ncgmpChecks.IsSysInfoPresent(openedWorkspace); // if (isValid == false) // { // MessageBox.Show("In order to use these tools, the NCGMP database must contain a SysInfo table.", "NCGMP Toolbar"); // goto findDatabase; // } //} #endregion // Show the copy form sourceLegendItemSelection sourceForm = new sourceLegendItemSelection(openedWorkspace); sourceForm.ShowDialog(); // Bail if they canceled if (sourceForm.Canceled == true) { return; } // Get the Ids from the form, then close it if (sourceForm.idsToCopy.Count == 0) { sourceForm.Close(); return; } List<string> idsToCopy = sourceForm.idsToCopy; sourceForm.Close(); // Build the Query to get the records to copy string sqlWhereClause = "DescriptionOfMapUnits_ID = '"; foreach (string idValue in idsToCopy) { sqlWhereClause += idValue + "' OR DescriptionOfMapUnits_ID = '"; } // Get the records if (sqlWhereClause == "DescriptionOfMapUnits_ID = '") { return; } DescriptionOfMapUnitsAccess sourceDmu = new DescriptionOfMapUnitsAccess(openedWorkspace); sourceDmu.AddDescriptionOfMapUnits(sqlWhereClause.Remove(sqlWhereClause.Length - 32)); // Get the next new Hierarchy Key string newHierarchy = GetNewHierarchyKey(); int newValue = int.Parse(newHierarchy.Substring(newHierarchy.Length - 4)); // Loop through the source records, add them to the target legend after adjusting the Hierarchy DescriptionOfMapUnitsAccess targetDmu = new DescriptionOfMapUnitsAccess(m_theWorkspace); foreach (KeyValuePair<string, DescriptionOfMapUnitsAccess.DescriptionOfMapUnit> sourceEntry in sourceDmu.DescriptionOfMapUnitsDictionary) { DescriptionOfMapUnitsAccess.DescriptionOfMapUnit sourceDmuEntry = sourceEntry.Value; string thisHierachyKey = newValue.ToString().PadLeft(4, '0'); targetDmu.NewDescriptionOfMapUnit(sourceDmuEntry.MapUnit, sourceDmuEntry.Name, sourceDmuEntry.FullName, sourceDmuEntry.Label, sourceDmuEntry.Age, sourceDmuEntry.Description, thisHierachyKey, sourceDmuEntry.ParagraphStyle, sourceDmuEntry.AreaFillRGB, sourceDmuEntry.AreaFillPatternDescription, commonFunctions.GetCurrentDataSourceID(), sourceDmuEntry.GeneralLithology, sourceDmuEntry.GeneralLithologyConfidence); newValue++; } // Save the target Dmu targetDmu.SaveDescriptionOfMapUnits(); // Refresh the tree ClearMapUnitInput(); PopulateMainLegendTree(); }
private void printSDEConnections(string sde) { try { // We use IWorkspacename2 so that it returns a ENCRYPTED_PASSWORD required // for the connection string in an MSD. IWorkspaceFactory2 wf = new SdeWorkspaceFactoryClass(); IWorkspace ws = wf.OpenFromFile(txtSDE.Text, 0); IDataset ds = (IDataset)ws; IWorkspaceName2 wn = (IWorkspaceName2)ds.FullName; List<string> dbconns = wn.ConnectionString.Split(';').ToList<string>(); foreach (string param in dbconns) { this.richTextBox2.Text += param + "\n"; } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 通过sde文件连接SDE /// </summary> /// <param name="sdeFile">sde的连接配置文件</param> /// <param name="message"></param> /// <returns></returns> public static IWorkspace OpenSdeWorkspace(string sdeFile, out string sdeUser, out string message) { message = string.Empty; sdeUser = string.Empty; IWorkspace pWorkSpace = null; IWorkspaceFactory pSdeFactory = null; try { if (string.IsNullOrEmpty(sdeFile)) { message = "获取连接文件出错"; return(null); } if (!File.Exists(sdeFile)) { message = "获取连接文件出错"; return(null); } pSdeFactory = new SdeWorkspaceFactoryClass(); IPropertySet pPropertySet = pSdeFactory.ReadConnectionPropertiesFromFile(sdeFile); if (pPropertySet == null) { message = "读取连接文件出错"; return(null); } string strServer = pPropertySet.GetProperty("SERVER").ToString(); string strPort = pPropertySet.GetProperty("INSTANCE").ToString(); sdeUser = pPropertySet.GetProperty("USER").ToString(); //if (NetAssist.CheckSDEConnecTion(strServer, Convert.ToInt32(strPort), out message) == false) //{ // return null; //} if (NetAssist.PingIP(strServer) == false) { message = "无法连接服务器"; return(null); } if (strPort == "5151") { if (NetAssist.PingPort(strServer, Convert.ToInt32(strPort)) == false) { message = "无法连接服务器"; return(null); } } pWorkSpace = pSdeFactory.OpenFromFile(sdeFile, 0); } catch (Exception ex) { LOG.Error("空间数据库打开错误,详情:" + ex.Message); // Console.WriteLine("空间数据库打开错误"); message = ex.Message; return(null); } return(pWorkSpace); }
protected override void OnClick() { findDatabase: // Check the registry // Find a Database IWorkspaceFactory wsFact = null; IWorkspace openedWorkspace = null; // Browse for a file, personal or SDE geodatabase IGxObjectFilter objectFilter = new GxFilterWorkspaces(); IGxObject openedObject = commonFunctions.OpenArcFile(objectFilter, "Please select an NCGMP database"); if (openedObject == null) { return; } // Check to see if it is a File, Personal or SDE database, create appropriate workspace factory string pathToOpen = null; IGxRemoteDatabaseFolder remoteDatabaseFolder; switch (openedObject.Category) { case "Personal Geodatabase": wsFact = new AccessWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "File Geodatabase": wsFact = new FileGDBWorkspaceFactoryClass(); pathToOpen = openedObject.FullName; break; case "Spatial Database Connection": wsFact = new SdeWorkspaceFactoryClass(); remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent; pathToOpen = remoteDatabaseFolder.Path + "\\" + openedObject.Name; break; case "Database Connection": wsFact = new SdeWorkspaceFactoryClass(); remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent; pathToOpen = remoteDatabaseFolder.Path + "\\" + openedObject.Name; break; default: break; } try { openedWorkspace = wsFact.OpenFromFile(pathToOpen, 0); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } // Check to see if the database is valid NCGMP bool isValid = ncgmpChecks.IsWorkspaceMinNCGMPCompliant(openedWorkspace); if (isValid == false) { MessageBox.Show("The selected database is not a valid NCGMP database.", "NCGMP Toolbar"); goto findDatabase; } //else //{ // isValid = ncgmpChecks.IsSysInfoPresent(openedWorkspace); // if (isValid == false) // { // MessageBox.Show("In order to use these tools, the NCGMP database must contain a SysInfo table.", "NCGMP Toolbar"); // goto findDatabase; // } //} //bool isTopologyUsed = ncgmpChecks.IsTopologyUsed(openedWorkspace); //bool hasStationTables = ncgmpChecks.IsAzgsStationAddinPresent(openedWorkspace); //bool hasStandardLithtables = ncgmpChecks.IsStandardLithAddinPresent(openedWorkspace); bool hasRepresentations = ncgmpChecks.AreRepresentationsUsed(openedWorkspace); // Add FeatureClasses and tables to the ArcMap Project AddLayersToMap(openedWorkspace, hasRepresentations); // isTopologyUsed, hasStationTables, // Populate the Data Sources combobox }
/// <summary> /// Kết nối với server bằng file *.sde /// </summary> /// <param name="connectionFile">C:\\myData\\Sample.sde</param> /// <returns></returns> public IWorkspace ArcSdeWorkspaceFromFile(String connectionFile) { IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass(); return workspaceFactory.OpenFromFile(connectionFile, 0); }
static void Main(string[] args) { File.WriteAllText(commissionProgress, "Starting at " + DateTime.Now.ToString()); Console.WriteLine("Starting at " + DateTime.Now.ToString()); bool editing = false; bool editOp = false; bool gotLic =false; IWorkspaceEdit wse = null; License lic = new License(); try { gotLic = lic.GetLicenses(); if(gotLic == false){ return ; } File.WriteAllText(commissionProgress, "Got licenses at " + DateTime.Now.ToString()); Console.WriteLine("Got licenses at " + DateTime.Now.ToString()); IWorkspaceFactory wsf = new SdeWorkspaceFactoryClass(); var ws = wsf.OpenFromFile(GetConfiguration("SDEConnectionFile"), 0); IFeatureWorkspace fws = ws as IFeatureWorkspace; if (args.Length > 0) { ((IVersion)fws).RefreshVersion(); return; } File.WriteAllText(commissionProgress, "Got workspace at " + DateTime.Now.ToString()); ((IVersion)fws).RefreshVersion(); File.WriteAllText(commissionProgress, "Refreshed the version at " + DateTime.Now.ToString()); Console.WriteLine("Refreshed the version at " + DateTime.Now.ToString()); Console.WriteLine("Got workspace at " + DateTime.Now.ToString()); wse = fws as IWorkspaceEdit ; wse.StartEditing(false); editing = true; wse.StartEditOperation(); File.WriteAllText(commissionProgress, "Started editing at " + DateTime.Now.ToString()); Console.WriteLine("Started editing at " + DateTime.Now.ToString()); editOp = true; bool foundTapPhase = false; int phaseToApply = 7; List<IFeature> newlyCreatedFeatures = new List<IFeature>(); ITable express_feature_table = fws.OpenTable("schneiderville.sde.mm_express_features"); File.WriteAllText(commissionProgress, "Opened express features table at " + DateTime.Now.ToString()); Console.WriteLine("Opened express features table at " + DateTime.Now.ToString()); //Console.ReadLine(); //return; /*var lines = File.ReadAllLines(GetConfiguration("CommisionedDesign")); string lastLayerName = ""; Dictionary<string, List<int>> layerToOIDS = new Dictionary<string, List<int>>(); foreach (string line in lines) { int oid = -1; if (int.TryParse(line, out oid) == false) { layerToOIDS.Add(line, new List<int>()); lastLayerName = line; } else { layerToOIDS[lastLayerName].Add(Convert.ToInt32(line)); } }*/ Console.WriteLine("Opening feature classes: " + DateTime.Now.ToString()); File.WriteAllText(commissionProgress, "Opening feature classes: " + DateTime.Now.ToString()); Dictionary<string, IFeatureClass> layerNamesToFeatureClasses = new Dictionary<string, IFeatureClass>(); #region open feature classes List<string> dxClassNames = new List<string>{ "DxBusbar","DxCabinetStructure","DxCapacitorBank","DxDownGuy", "DxDynamicProtectiveDevice","DxFuse","DxGenerator","DxLight", "DxPriOHElectricLineSegment","DxPriUGElectricLineSegment","DxSecOHElectricLineSegment","DxSecUGElectricLineSegment", "DxRecloser","DxRiser","DxSectionalizer", "DxServicePoint","DxSpanGuy","DxSupportStructure", "DxSurfaceStructure","DxSwitch","DxTransformer","DxVoltageRegulatorBank"}; foreach (string dxClassName in dxClassNames) { string key = "Schneiderville.ARCFM." + dxClassName; IFeatureClass fc = fws.OpenFeatureClass(key); layerNamesToFeatureClasses.Add(key, fc); string correspondingClass = key.Replace("Dx", ""); IFeatureClass correspondingFC = fws.OpenFeatureClass(correspondingClass); layerNamesToFeatureClasses.Add(correspondingClass, correspondingFC); } #endregion //WriteGeometry(layerNamesToFeatureClasses); //Now that we have opened the workspace, a table, and gotten the license, we spin and wait for the file to alert us that we are ready to proced string requestOriginal = File.ReadAllText(GetConfiguration("RequestCommission")); Console.WriteLine("waiting patiently..." + DateTime.Now.ToString()); File.WriteAllText(commissionProgress, "Awating commissiong..." + DateTime.Now.ToString()); while (true) { System.Threading.Thread.Sleep(1000); if (requestOriginal != File.ReadAllText(GetConfiguration("RequestCommission"))) { break; } } var lines = File.ReadAllLines(GetConfiguration("CommisionedDesign")); string lastLayerName = ""; Dictionary<string, List<int>> layerToOIDS = new Dictionary<string, List<int>>(); foreach (string line in lines) { int oid = -1; if (int.TryParse(line, out oid) == false) { layerToOIDS.Add(line, new List<int>()); lastLayerName = line; } else { layerToOIDS[lastLayerName].Add(Convert.ToInt32(line)); } } Console.WriteLine("Starting to commission at: " + DateTime.Now.ToString()); File.WriteAllText(commissionProgress, "Starting to commission at: " + DateTime.Now.ToString()); foreach (KeyValuePair<string, List<int>> kvp in layerToOIDS) { IFeatureClass source =layerNamesToFeatureClasses[kvp.Key]; //fws.OpenFeatureClass(kvp.Key); IFeatureClass target = layerNamesToFeatureClasses[kvp.Key.Replace("Dx", "")];//fws.OpenFeatureClass(kvp.Key.Replace("Dx", "")); int counter = 0; foreach (int oid in kvp.Value) { IFeature newFeature = target.CreateFeature(); IFeature sourceFeature = null; try { sourceFeature = source.GetFeature(oid); } catch { if (sourceFeature == null) { File.WriteAllText(commissionProgress, "Source feature is null " + DateTime.Now.ToString()); continue; } } #region Looop through fields setting values on new features for (int i = 0; i < source.Fields.FieldCount; i++) { try { string fieldName = source.Fields.get_Field(i).Name; if (fieldName.ToUpper() != "OBJECTID") { object sourceValue = sourceFeature.get_Value(i); newFeature.set_Value(newFeature.Fields.FindField(fieldName), sourceValue); } } catch { } } #endregion try { #region if we haven't found a phase if (!foundTapPhase) { List<IPoint> points = new List<IPoint>(); if (newFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint) { //points.Add(newFeature.ShapeCopy as IPoint); } else { IPolyline pl = newFeature.ShapeCopy as IPolyline; points.Add(pl.FromPoint); points.Add(pl.ToPoint); } foreach (IPoint pnt in points) // start and end points of line { IEnumFeature enFes = (newFeature as INetworkFeature).GeometricNetwork.SearchForNetworkFeature(pnt, esriFeatureType.esriFTComplexEdge); enFes.Reset(); IFeature fe = enFes.Next(); #region loop through connected features while (fe != null) { object pd = fe.get_Value(fe.Fields.FindField("PHASEDESIGNATION")); if (pd != DBNull.Value) { short pdShort = 0; Int16.TryParse(pd.ToString(), out pdShort); phaseToApply = pdShort; //Now, the phase to apply might be a two or three phase, but the new feature might be a single phase int subtype = ((IRowSubtypes)newFeature).SubtypeCode; if (subtype == 1) { if (phaseToApply == 7) //ABC { phaseToApply = 4;//A } if (phaseToApply == 6) //AB (4+2) { phaseToApply = 4;//A } if (phaseToApply == 5) //AC (4+1) { phaseToApply = 4;//A } if (phaseToApply == 3) //BC (2+1) { phaseToApply = 2;//B } } Console.WriteLine("Tap phase found (" + phaseToApply + ") at " + DateTime.Now.ToString()); File.WriteAllText(commissionProgress, "Tap phase found (" + phaseToApply + ") at " + DateTime.Now.ToString()); foundTapPhase = true; } fe = enFes.Next(); } #endregion } } #endregion } catch (Exception ex) { } newFeature.Store(); newlyCreatedFeatures.Add(newFeature); int objectClassID = sourceFeature.Class.ObjectClassID; int featureOID = sourceFeature.OID; IQueryFilter qf = new QueryFilterClass(); qf.WhereClause = "FEATURECLASSID = " + objectClassID + " AND FEATUREOID = " + featureOID; ICursor expressCur = express_feature_table.Search(qf, false); IRow expressFeRow = expressCur.NextRow(); try { expressFeRow.Delete(); //sourceFeature.Delete(); Console.WriteLine("Created one new feature and deleted a row from express_features table: " + DateTime.Now.ToString()); counter++; File.WriteAllText(commissionProgress, "Created feature #" + counter + " and deleted corresponding row from express_features table: " + DateTime.Now.ToString()); } catch { //Swallow errors where we can't delete features in express features table. } } } foreach (IFeature newFe in newlyCreatedFeatures) { int pdIndex = newFe.Fields.FindField("PHASEDESIGNATION"); if (pdIndex > -1) { newFe.set_Value(pdIndex, phaseToApply); newFe.Store(); Console.WriteLine("Set Phase on " + newFe.Class.AliasName + " " + newFe.OID + " : " + DateTime.Now.ToString()); File.WriteAllText(commissionProgress, "Set Phase on " + newFe.Class.AliasName + " " + newFe.OID + " : " + DateTime.Now.ToString()); } } } catch (Exception ex) { Console.WriteLine("ERROR - " + ex.ToString()); File.WriteAllText(commissionProgress, "Unfortunately, an error occurred"); Console.ReadLine(); } finally { if (editOp) { wse.StopEditOperation(); } if (editing) { wse.StopEditing(true); } if (wse != null) { ((IVersion)wse).RefreshVersion(); } lic.ReleaseLicenses(); Console.WriteLine("Released licenses at: " + DateTime.Now.ToString()); File.WriteAllText(commissionProgress, "Released licenses at: " + DateTime.Now.ToString()); File.WriteAllText(commissionProgress, "Commissioning complete at: " + DateTime.Now.ToString()); File.WriteAllText(GetConfiguration("TimeDone") , DateTime.Now.ToString()); Console.ReadLine(); } }