/// <summary> /// deletes a given version /// </summary> /// <param name="versname">version name</param> /// <param name="sdeConn">parent sde connection</param> /// <returns>true if success otherwise false</returns> public bool deleteSDEVersion(string versname, string sdeConn) { bool x = true; try { IWorkspace wks; IWorkspaceFactory wsFact; IPropertySet propSet; string parentVersion = null; if (sdeConn == null) { propSet = getProjectPS(); wsFact = new SdeWorkspaceFactoryClass(); wks = wsFact.Open(propSet, 0); } else { wks = OpenWorkSpace(sdeConn); propSet = wks.ConnectionProperties; wsFact = wks.WorkspaceFactory; } IVersionedWorkspace3 vwks = wks as IVersionedWorkspace3; IEnumVersionInfo eVinfo = vwks.Versions; IVersionInfo vinfo = eVinfo.Next(); IVersion version = null; while (vinfo != null) { string vName = vinfo.VersionName; if (vName.ToLower().EndsWith(versname.ToLower())) { parentVersion = vName; version = vwks.FindVersion(vName); break; } vinfo = eVinfo.Next(); } if (version != null) { version.Delete(); } else { Console.WriteLine("Error: Could not find Version"); x = false; } } catch(Exception e) { x = false; Console.WriteLine("Error: " + e.ToString()); } return x; }
/// <summary> /// 设置SDE工作区 /// </summary> /// <param name="sServer">服务器名</param> /// <param name="sService">服务名</param> /// <param name="sDatabase">数据库名(SQLServer)</param> /// <param name="sUser">用户名</param> /// <param name="sPassword">密码</param> /// <param name="strVersion">SDE版本</param> /// <returns>输出错误Exception</returns> public bool SetWorkspace(string sServer, string sService, string sDatabase, string sUser, string sPassword, string strVersion, out Exception eError) { eError = null; IPropertySet pPropSet = new PropertySetClass(); IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass(); 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 { m_Workspace = pSdeFact.Open(pPropSet, 0); pPropSet = null; pSdeFact = null; m_connset = "SDE;" + sServer + "|" + sService + "|" + sDatabase + "|" + sUser + "|" + sPassword + "|" + strVersion; return(true); } catch (Exception eX) { return(false); } }
//-------------------------------------------------------------------------------- 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); } }
private IWorkspace CreateWorkspace() { try { IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass(); IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("SERVER", this.Server); propertySet.SetProperty("INSTANCE", this.Instance); propertySet.SetProperty("DATABASE", this.Database); propertySet.SetProperty("USER", this.User); propertySet.SetProperty("PASSWORD", this.PassWord); propertySet.SetProperty("VERSION", this.Version); propertySet.SetProperty("AUTHENTICATION_MODE", this.Authentication_Mode); IWorkspace workspace = workspaceFactory.Open(propertySet, 0); return(workspace); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.ToString()); } return(null); }
/// <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); }
private IWorkspace method_4() { IWorkspaceFactory factory = new SdeWorkspaceFactoryClass(); try { return(factory.Open(this.method_2(), 0)); } catch (Exception exception) { if (exception is COMException) { switch (((uint)(exception as COMException).ErrorCode)) { case 2147751273: case 2147751169: MessageBox.Show("连接数据库失败", "连接"); return(null); case 2147751274: MessageBox.Show("连接数据库失败\r\n该服务器上的SDE没有启动", "连接"); return(null); case 2147500037: MessageBox.Show("连接数据库失败", "连接"); return(null); } } Logger.Current.Error("", exception, ""); } return(null); }
//直连 private void directConnect() { IWorkspaceFactory pWorkspaceFactory = new SdeWorkspaceFactoryClass(); IWorkspace pWorkspace = pWorkspaceFactory.Open(CreatePropertySet("", "sde:postgresql:192.168.0.40", "sde", "hy@123456", "sde.DEFAULT", "sde", true), 0); DebugInfo(pWorkspace); }
/// <summary> /// 获得所有SDE图层 /// </summary> private void GetAllSDELayer() { //SDE直接连接函数 IPropertySet propset = SDEDirectConnection(); //定义一个工作空间, 并实例化为SDE的工作空间类 IWorkspaceFactory workspaceFactroy = new SdeWorkspaceFactoryClass(); //打开SDE工作空间 IWorkspace workspace = workspaceFactroy.Open(propset, 0); //通过工作空间获取要素类,并存放在List<string>的泛型类中 List <string> listFeatureClass = GetFeatureClassByWorkspace(workspace); //定义个变量i,用来获取图层 int i = 0; //使用foreach循环来遍历listFeatureClass foreach (var item in listFeatureClass) { //将工作空间强转成要素工作空间 IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; //通过要素空间打开要素类并存放在要素类中 IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(item); //新建一个要素图层 IFeatureLayer featureLayer = new FeatureLayer(); //将要素类存放在刚定义好的要素图层的要素类中 featureLayer.FeatureClass = featureClass; //设置要素图层名字 featureLayer.Name = featureClass.AliasName; //axMapControl1增加图层 axMapControl1.AddLayer(featureLayer, i); //自增i i++; } //刷新axMapControl1 axMapControl1.Refresh(); }
// // 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> /// 为SDE的Workspace生成GP字符串 /// @remark 方法是在系统目录的根目录下生成Temp.SDE,并用此文件来生成字符串 /// </summary> /// <param name="wsTarget"></param> /// <param name="featureDatasetName"></param> /// <param name="featureClassName"></param> /// <returns></returns> public static string GetGpString(IWorkspace wsTarget, string featureDatasetName, string featureClassName) { if (wsTarget == null) return null; try { string strTempPath = System.IO.Path.GetPathRoot(global::System.Environment.SystemDirectory); // System.IO.Path.Combine(System.IO.Path.GetPathRoot(Environment.SystemDirectory), "SDETemp"); string strTempName = "Temp"; string strGpString = System.IO.Path.Combine(strTempPath, strTempName+".SDE"); IPropertySet propertySet = wsTarget.ConnectionProperties; IWorkspaceFactory wsfSDE = new SdeWorkspaceFactoryClass(); if (System.IO.File.Exists(strGpString)) { System.IO.File.Delete(strGpString); } wsfSDE.Create(strTempPath, strTempName, propertySet, 0); if (!string.IsNullOrEmpty(featureDatasetName)) { //strGpString = System.IO.Path.Combine(strGpString, featureDatasetName); return string.Format("{0}\\{1}\\{2}", strGpString, featureDatasetName, featureClassName); } else { return string.Format("{0}.{1}", strGpString, featureClassName); } } catch { return null; } }
//函数名:openSDEWorkspace //函数功能:create and open the sde workspace based on the provided information // public IWorkspace openSDEWorkspace(string Server, string Instance, string User, string Password, string Database, string version) { IWorkspace ws = null; try { IPropertySet pPropSet = new PropertySetClass(); IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass(); pPropSet.SetProperty("SERVER", Server); pPropSet.SetProperty("INSTANCE", Instance); pPropSet.SetProperty("DATABASE", Database); pPropSet.SetProperty("USER", User); pPropSet.SetProperty("PASSWORD", Password); pPropSet.SetProperty("VERSION", version); ws = pSdeFact.Open(pPropSet, 0); return(ws); } catch { return(ws); //if (e is StackOverflowException || // e is OutOfMemoryException) // throw; } }
// Handle exception and continue // executing. //*************************Raster Create End*************************** //**************************Raster Open Begin************************** //函数名: OpenRasterDatasetFromSDE //函数功能:在SDE中获得RasterDataset //参数: rasterDatasetName函数名。 //备注: //Libraries needed to run this code: //ESRI.ArcGIS.esriSystem, ESRI.ArcGIS.Geodatabase, ESRI.ArcGIS.DataSourcesGDB public IRasterDataset OpenRasterDatasetFromSDE(string server, string instance, string database, string user, string password, string rasterDatasetName, string version) { // Open an ArcSDE raster dataset with the given name // server, instance, database, user, password, version are database connection info // rasterDatasetName is the name of the raster dataset to be opened//Open the ArcSDE workspace 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); // cocreate the workspace factory IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass(); // Open the raster workspace using the previously defined porperty set and // QI to the desired IRasterWorkspaceEx interface to access the existing dataset IRasterWorkspaceEx rasterWorkspaceEx = workspaceFactory.Open(propertySet, 0) as IRasterWorkspaceEx; //Open the ArcSDE raster dataset IRasterDataset rasterDataset = null; rasterDataset = rasterWorkspaceEx.OpenRasterDataset(rasterDatasetName); return(rasterDataset); }
/// <summary> /// 给指定的WorkspaceName生成GP字符串 /// </summary> /// <param name="wsNameTarget"></param> /// <returns></returns> public static string GetGpString(IWorkspaceName wsNameTarget) { if (wsNameTarget == null) { return(null); } if (wsNameTarget.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) { try { string strTempPath = System.IO.Path.GetPathRoot(System.Environment.SystemDirectory); // System.IO.Path.Combine(System.IO.Path.GetPathRoot(Environment.SystemDirectory), "SDETemp"); string strTempName = string.Format("Temp_{0}", wsNameTarget.GetHashCode()); string strGpString = System.IO.Path.Combine(strTempPath, strTempName + ".SDE"); IPropertySet propertySet = wsNameTarget.ConnectionProperties; IWorkspaceFactory wsfSDE = new SdeWorkspaceFactoryClass(); if (System.IO.File.Exists(strGpString)) { System.IO.File.Delete(strGpString); } wsfSDE.Create(strTempPath, strTempName, propertySet, 0); return(strGpString); } catch { return(null); } } else { return(wsNameTarget.PathName); } }
private IWorkspace OpenSDEWorkspace(string server, string instance, string database, string user, string password, string version) { try { IPropertySet propSet = new PropertySetClass(); if (server.Trim() != string.Empty) { propSet.SetProperty("SERVER", server); } propSet.SetProperty("INSTANCE", instance); propSet.SetProperty("DATABASE", database); propSet.SetProperty("USER", user); propSet.SetProperty("PASSWORD", password); propSet.SetProperty("VERSION", version); IWorkspaceFactory wsf = new SdeWorkspaceFactoryClass(); return(wsf.Open(propSet, 0)); } catch (Exception e) { MessageBox.Show(e.Message); return(null); } }
/// <summary> /// 如果是SDE库体则获取工作空间 /// </summary> /// <param name="propertySet">工作空间连接属性</param> public GOFuzingTables(IPropertySet propertySet) { IWorkspaceFactory pWorkspaceFactory = new SdeWorkspaceFactoryClass(); this._Workspace = pWorkspaceFactory.Open(propertySet, 0); this._TempleteWorkspace = OpenTempleteWorkSpace(); }
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 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; } }
private void btnTestConnection_Click(object sender, EventArgs e) { System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; IPropertySet connectionProperties = new PropertySetClass(); string str = this.txtServer.Text.Trim(); connectionProperties.SetProperty("SERVER", str); str = this.txtInstance.Text.Trim(); connectionProperties.SetProperty("INSTANCE", str); str = this.txtDatabase.Text.Trim(); if (str.Length >= 0) { connectionProperties.SetProperty("DATABASE", str); } str = this.txtUser.Text.Trim(); connectionProperties.SetProperty("USER", str); str = this.txtPassword.Text.Trim(); connectionProperties.SetProperty("PASSWORD", str); connectionProperties.SetProperty("VERSION", this.string_1); IWorkspaceFactory factory = new SdeWorkspaceFactoryClass(); try { factory.Open(connectionProperties, 0); this.bool_0 = true; this.btnTestConnection.Enabled = false; } catch (Exception exception) { MessageBox.Show(exception.Message); } System.Windows.Forms.Cursor.Current = Cursors.Default; }
private IWorkspace open_ArcSDE_Workspace(string server, string instance, string user, string password, string database, string version, out string serr) { try { ///IPropertySet接口提供对用于管理PropertySet的成员的访问。IPropertySet接口包含在PropertySet中设置和检索命名值对集合的方法。 ///PropertySet是一个通用类,用于保存任何东西的一组属性。使用属性集的一个示例是保存打开SDE工作空间所需的属性,如示例代码所示。 ///通常,属性集可以被认为是一组键(字符串)和值(变体/对象)。一个值得注意的例外是在XmlPropertySet对象上使用IPropertySet接口。 XML文档可以包含具有相同名称的多个元素(即“属性/子”)和不同的值。因此,此接口从XmlPropertySet返回的值可能是锯齿状的二维数组(包含其他数组的数组)。有关更多详细信息和代码示例,请参阅Geodatabase库中的XmlPropertySet coclass'文档。 IPropertySet connectionProperties = new PropertySetClass(); connectionProperties.SetProperty("SERVER", server); connectionProperties.SetProperty("INSTANCE", instance); connectionProperties.SetProperty("DATABASE", database); connectionProperties.SetProperty("USER", user); connectionProperties.SetProperty("PASSWORD", password); connectionProperties.SetProperty("VERSION", version); IWorkspaceFactory factory = new SdeWorkspaceFactoryClass(); IWorkspace workspace = factory.Open(connectionProperties, 0); serr = ""; return(workspace); } catch (Exception exception) { this.mErrOpt.ErrorOperate(this.mSubSysName, "FunFactory.WorkspaceFun", "open_ArcSDE_Workspace", exception.GetHashCode().ToString(), exception.Source, exception.Message, "", "", ""); serr = exception.Message; return(null); } }
//基于服务的连接 private void baseOnSDE() { IWorkspaceFactory pWorkspaceFactory = new SdeWorkspaceFactoryClass(); IWorkspace pWorkspace = pWorkspaceFactory.Open(CreatePropertySet("192.168.0.40", "5151", "sde", "hy@123456", "sde.DEFAULT", "sde", false), 0); DebugInfo(pWorkspace); }
//根据连接字符串获取工作空间 //此处连接字符串是固定格式的连接串 Server|Service|Database|User|Password|Version private static IWorkspace GetWorkSpacefromConninfo(string conninfostr, int type) { if (conninfostr == "") { return(null); } if (type < 0) { return(null); } int index1 = conninfostr.IndexOf("|"); int index2 = conninfostr.IndexOf("|", index1 + 1); int index3 = conninfostr.IndexOf("|", index2 + 1); int index4 = conninfostr.IndexOf("|", index3 + 1); int index5 = conninfostr.IndexOf("|", index4 + 1); int index6 = conninfostr.IndexOf("|", index5 + 1); IPropertySet pPropSet = new PropertySetClass(); IWorkspaceFactory pWSFact = null; string sServer = ""; string sService = ""; string sDatabase = ""; string sUser = ""; string sPassword = ""; string strVersion = ""; switch (type) { case 1: //mdb pWSFact = new AccessWorkspaceFactoryClass(); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); break; case 2: //gdb pWSFact = new FileGDBWorkspaceFactoryClass(); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); break; case 3: //sde pWSFact = new SdeWorkspaceFactoryClass(); sServer = conninfostr.Substring(0, index1); sService = conninfostr.Substring(index1 + 1, index2 - index1 - 1); sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1); sUser = conninfostr.Substring(index3 + 1, index4 - index3 - 1); sPassword = conninfostr.Substring(index4 + 1, index5 - index4 - 1); strVersion = conninfostr.Substring(index5 + 1, index6 - index5 - 1); break; } pPropSet.SetProperty("SERVER", sServer); pPropSet.SetProperty("INSTANCE", sService); pPropSet.SetProperty("DATABASE", sDatabase); pPropSet.SetProperty("USER", sUser); pPropSet.SetProperty("PASSWORD", sPassword); pPropSet.SetProperty("VERSION", strVersion); try { IWorkspace pWorkspace = pWSFact.Open(pPropSet, 0); return(pWorkspace); } catch { return(null); } }
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; }
/// <summary> /// 设置SDE工作区 /// </summary> /// <param name="sServer">服务器名</param> /// <param name="sService">服务名</param> /// <param name="sDatabase">数据库名(SQLServer)</param> /// <param name="sUser">用户名</param> /// <param name="sPassword">密码</param> /// <param name="strVersion">SDE版本</param> /// <returns>输出错误Exception</returns> public IWorkspace SetWorkspace(string sServer, string sService, string sDatabase, string sUser, string sPassword, string strVersion) { //eError = null; IPropertySet pPropSet = new PropertySetClass(); IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass(); 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 { return(pSdeFact.Open(pPropSet, 0)); } catch (Exception eX) { //******************************** //guozheng added system exception log //if (SysCommon.Log.Module.SysLog == null) // SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); //SysCommon.Log.Module.SysLog.Write(eX); //******************************** return(null); } }
/// <summary> /// 设置SDE工作区 /// </summary> /// <param name="sServer">服务器名</param> /// <param name="sService">服务名</param> /// <param name="sDatabase">数据库名(SQLServer)</param> /// <param name="sUser">用户名</param> /// <param name="sPassword">密码</param> /// <param name="strVersion">SDE版本</param> /// <returns>输出错误Exception</returns> private IWorkspace SetWorkspace(string sServer, string sService, string sDatabase, string sUser, string sPassword, string strVersion, out Exception eError) { eError = null; IWorkspace pWks = null; IPropertySet pPropSet = new PropertySetClass(); IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass(); 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 { pWks = pSdeFact.Open(pPropSet, 0); pPropSet = null; pSdeFact = null; return(pWks); } catch (Exception eX) { eError = eX; return(null); } }
private void refreshSDEFiles() { lstSDE.Items.Clear(); pHashtable.Clear(); string[] Files = System.IO.Directory.GetFiles(sDir, "*.sde"); foreach (string file in Files) { IWorkspaceFactory pWSF = new SdeWorkspaceFactoryClass(); IPropertySet ppro = pWSF.ReadConnectionPropertiesFromFile(file); if (ppro != null) { object strnames = null; object strvalues = null; int count = ppro.Count; ppro.GetAllProperties(out strnames, out strvalues); object po = ppro.GetProperty("PASSWORD"); string[] strN = strnames as string[]; int ipos = file.LastIndexOf("\\"); string strFileName = file.Substring(ipos + 1, file.Length - ipos - 1); lstSDE.Items.Add(strFileName); pHashtable.Add(strFileName, ppro); } } }
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; } }
//测试 private void buttonXTest_Click(object sender, EventArgs e) { if (cboDataType.Text == "SDE") { try {//Workspace IWorkspaceFactory pWorkspaceFactory; pWorkspaceFactory = new SdeWorkspaceFactoryClass(); //PropertySet IPropertySet pPropertySet; pPropertySet = new PropertySetClass(); //pPropertySet.SetProperty("Service", comboBoxDsName.Text); pPropertySet.SetProperty("Server", txtServer.Text); pPropertySet.SetProperty("Database", txtDataBase.Text); pPropertySet.SetProperty("Instance", "5151");//"port:" + txtService.Text pPropertySet.SetProperty("user", txtUser.Text); pPropertySet.SetProperty("password", txtPassWord.Text); pPropertySet.SetProperty("version", "sde.DEFAULT"); IWorkspace pws = pWorkspaceFactory.Open(pPropertySet, 0); MessageBox.Show("连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("连接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } if (cboDataType.Text == "PDB") { if (txtServer.Text == "") { MessageBox.Show("服务器名为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { IWorkspaceFactory pWorkspaceFactory; pWorkspaceFactory = new AccessWorkspaceFactoryClass(); IWorkspace pws = pWorkspaceFactory.OpenFromFile(txtServer.Text, 0); MessageBox.Show("连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("连接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } if (cboDataType.Text == "GDB") { if (txtServer.Text == "") { MessageBox.Show("服务器名为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { IWorkspaceFactory pWorkspaceFactory; pWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); IWorkspace pws = pWorkspaceFactory.OpenFromFile(txtServer.Text, 0); MessageBox.Show("连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("连接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
public static IFeatureClass GetFeatureInSde(IPropertySet properties, string featureClassName) { SdeWorkspaceFactory sdeWorkspaceFactory = new SdeWorkspaceFactoryClass(); var workspace = sdeWorkspaceFactory.Open(properties, 0); var fc = ((IFeatureWorkspace)workspace).OpenFeatureClass(featureClassName); return(fc); }
public void ChangeHistoricalVersionByTimeStamp(IGraphicsContainer igraphicsContainer_0, IFeatureWorkspace ifeatureWorkspace_0, object object_0) { try { if ((((igraphicsContainer_0 != null) && (ifeatureWorkspace_0 != null)) && (object_0 != null)) && (ifeatureWorkspace_0 is IHistoricalWorkspace)) { object obj2; object obj3; (ifeatureWorkspace_0 as IWorkspace).ConnectionProperties.GetAllProperties(out obj2, out obj3); IPropertySet connectionProperties = new PropertySetClass(); for (int i = 0; i < ((System.Array)obj2).Length; i++) { switch (((System.Array)obj2).GetValue(i).ToString().ToUpper()) { case "SERVER": connectionProperties.SetProperty("SERVER", ((System.Array)obj3).GetValue(i)); break; case "INSTANCE": connectionProperties.SetProperty("INSTANCE", ((System.Array)obj3).GetValue(i)); break; case "DATABASE": connectionProperties.SetProperty("DATABASE", ((System.Array)obj3).GetValue(i)); break; case "USER": connectionProperties.SetProperty("USER", ((System.Array)obj3).GetValue(i)); break; case "PASSWORD": connectionProperties.SetProperty("PASSWORD", ((System.Array)obj3).GetValue(i)); break; case "AUTHENTICATION_MODE": connectionProperties.SetProperty("AUTHENTICATION_MODE", ((System.Array)obj3).GetValue(i)); break; } } connectionProperties.SetProperty("HISTORICAL_TIMESTAMP", object_0); connectionProperties.GetAllProperties(out obj2, out obj3); IWorkspaceFactory factory = new SdeWorkspaceFactoryClass(); IWorkspace workspace = factory.Open(connectionProperties, 0); if (workspace != null) { workspace.ConnectionProperties.GetAllProperties(out obj2, out obj3); this.ChangeVersion(igraphicsContainer_0, ifeatureWorkspace_0, workspace as IFeatureWorkspace); } } } catch (Exception exception) { MessageBox.Show(exception.Message); } }
//not finished public static void BurstFindValves() { // run a FindPath between 2 flags, create a polyline from the results //需要desktop,放弃 /* * INetworkAnalysisExt pNetAnalysisExt; * INetworkAnalysisExtFlags pNetAnalysisExtFlags; * INetworkAnalysisExtBarriers pNetAnalysisExtBarriers; * INetworkAnalysisExtResults pNetAnalysisExtResults; */ string valvelayername = "Water Fixtures"; string waterlinelayername = "Water Lines"; string waternetworkname = "Water_Network"; INetworkCollection pNetworkCollection; IFeatureDataset pFeatureDataSet; IWorkspaceFactory pWSF = new SdeWorkspaceFactoryClass(); IPropertySet pPropset = new PropertySetClass(); IFeatureWorkspace pFeatureWorkspace = pWSF.Open(pPropset, 0) as IFeatureWorkspace; INetwork pNetwork; IGeometricNetwork pGeometricNetwork; pFeatureDataSet = pFeatureWorkspace.OpenFeatureDataset("datasetName"); pNetworkCollection = pFeatureDataSet as INetworkCollection; pGeometricNetwork = pNetworkCollection.get_GeometricNetworkByName("networkname"); pNetwork = pGeometricNetwork.Network; IEdgeFlagDisplay pEdgeFlagDisplay; IFlagDisplay pFlagDisplay; IEdgeFlag pEdgeFlag; INetFlag pNetFlag; //创建一个flag pEdgeFlag = new EdgeFlagClass(); pNetFlag = pEdgeFlag as INetFlag; IFeatureLayer pFeatLayerValves; IFeatureLayer pFeatLayerWaterLines; UID pID = new UIDClass(); }
/// <summary> /// 构造函数 /// </summary> /// <param name="propertySet">保存的连接设置</param> /// <param name="DBType">目标的类型(PDB、SDE、GDB)</param> /// <param name="pDesProperty">目标的连接设置</param> public GOFuzingSpatialTables(IPropertySet propertySet, string DBType, IPropertySet pDesProperty) { this._DesDBType = DBType; this._PropertySet = pDesProperty; IWorkspaceFactory pWorkspaceFactory = new SdeWorkspaceFactoryClass(); this._Workspace = pWorkspaceFactory.Open(propertySet, 0); this._TempleteWorkspace = OpenTempleteWorkSpace(); }
public static IWorkspace GetSdeWorkspace(object psObj) { var dic = (Dictionary <string, object>)psObj; var ps = dic.ToPropertySet(); SdeWorkspaceFactory wf = new SdeWorkspaceFactoryClass(); var ws = wf.Open(ps, 0); return(ws); }
//----------------------------------------------------------------------------------------------------- public static IWorkspace openSDEWorkspace(String connectionString) { //ESRI.ArcGIS.Geodatabase.IWorkspaceFactory2 workspaceFactory; //workspaceFactory = (ESRI.ArcGIS.Geodatabase.IWorkspaceFactory2)new //ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass(); IWorkspaceFactory2 workspaceFactory = new SdeWorkspaceFactoryClass(); return(workspaceFactory.OpenFromString(connectionString, 0)); }
//not finished public static void BurstFindValves() { // run a FindPath between 2 flags, create a polyline from the results //��Ҫdesktop������ /* INetworkAnalysisExt pNetAnalysisExt; INetworkAnalysisExtFlags pNetAnalysisExtFlags; INetworkAnalysisExtBarriers pNetAnalysisExtBarriers; INetworkAnalysisExtResults pNetAnalysisExtResults; */ string valvelayername = "Water Fixtures"; string waterlinelayername = "Water Lines"; string waternetworkname = "Water_Network"; INetworkCollection pNetworkCollection; IFeatureDataset pFeatureDataSet; IWorkspaceFactory pWSF=new SdeWorkspaceFactoryClass(); IPropertySet pPropset=new PropertySetClass(); IFeatureWorkspace pFeatureWorkspace=pWSF.Open(pPropset,0) as IFeatureWorkspace; INetwork pNetwork; IGeometricNetwork pGeometricNetwork; pFeatureDataSet = pFeatureWorkspace.OpenFeatureDataset("datasetName"); pNetworkCollection=pFeatureDataSet as INetworkCollection; pGeometricNetwork=pNetworkCollection.get_GeometricNetworkByName("networkname"); pNetwork=pGeometricNetwork.Network; IEdgeFlagDisplay pEdgeFlagDisplay; IFlagDisplay pFlagDisplay; IEdgeFlag pEdgeFlag; INetFlag pNetFlag; //����һ��flag pEdgeFlag=new EdgeFlagClass(); pNetFlag=pEdgeFlag as INetFlag; IFeatureLayer pFeatLayerValves; IFeatureLayer pFeatLayerWaterLines; UID pID=new UIDClass(); }
/// <summary> /// 打开Workspace /// </summary> /// <param name="wsType"></param> /// <param name="objWorkspace">当为SDE时使用IPropertySet,其余情况使用路径(string)</param> /// <returns></returns> public static IWorkspace OpenWorkspace(enumWorkspaceType wsType, object objWorkspace) { IWorkspaceFactory wsf = null; try { switch (wsType) { case enumWorkspaceType.FileGDB: wsf = new FileGDBWorkspaceFactoryClass(); return wsf.OpenFromFile(objWorkspace as string, 0); case enumWorkspaceType.PGDB: wsf = new AccessWorkspaceFactoryClass(); return wsf.OpenFromFile(objWorkspace as string, 0); case enumWorkspaceType.File: wsf = new ShapefileWorkspaceFactoryClass(); return wsf.OpenFromFile(objWorkspace as string, 0); case enumWorkspaceType.SDE: wsf = new SdeWorkspaceFactoryClass(); IPropertySet pSet = objWorkspace as IPropertySet; if (pSet == null) { string strArgs = objWorkspace as string; pSet = new PropertySetClass(); string[] argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string strArg in argList) { string[] argPair = strArg.Split(new char[] { '=' }); pSet.SetProperty(argPair[0], argPair[1]); } } return wsf.Open(pSet, 0); } } catch { return null; } finally { if (wsf != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(wsf); } return null; }
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); } } }
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(); }
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; } }
/// <summary> /// 给指定的WorkspaceName生成GP字符串 /// </summary> /// <param name="wsNameTarget"></param> /// <returns></returns> public static string GetGpString(IWorkspaceName wsNameTarget) { if (wsNameTarget == null) return null; if (wsNameTarget.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) { try { string strTempPath = System.IO.Path.GetPathRoot(System.Environment.SystemDirectory); // System.IO.Path.Combine(System.IO.Path.GetPathRoot(Environment.SystemDirectory), "SDETemp"); string strTempName = string.Format("Temp_{0}", wsNameTarget.GetHashCode()); string strGpString = System.IO.Path.Combine(strTempPath, strTempName + ".SDE"); IPropertySet propertySet = wsNameTarget.ConnectionProperties; IWorkspaceFactory wsfSDE = new SdeWorkspaceFactoryClass(); if (System.IO.File.Exists(strGpString)) { System.IO.File.Delete(strGpString); } wsfSDE.Create(strTempPath, strTempName, propertySet, 0); return strGpString; } catch { return null; } } else { return wsNameTarget.PathName; } }
/// <summary> /// Conecta a uma workspace SDE /// </summary> private void OpenSdeWorkspace() { var factory = new SdeWorkspaceFactoryClass(); IPropertySet set = new PropertySet(); set.SetProperty("server", _server); set.SetProperty("instance", _instance); set.SetProperty("user", _user); set.SetProperty("version", _version); set.SetProperty("password", _password); try { workspace = factory.Open(set, 0); isOpened = true; } catch (Exception e) { isOpened = false; throw new InvalidOperationException(string.Format("Error to connected in SDE: {0}", e.Message), e); } }
/// <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); }
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 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 static IWorkspace arcSDEWorkspaceOpen(string server, string instance, string user, string password, string database, string version) { IPropertySet pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("SERVER", server); pPropertySet.SetProperty("INSTANCE", instance); pPropertySet.SetProperty("USER", user); pPropertySet.SetProperty("PASSWORD", password); pPropertySet.SetProperty("DATABASE", database); pPropertySet.SetProperty("VERSION", version); IWorkspaceFactory2 pWorkspaceFactory = new SdeWorkspaceFactoryClass(); IWorkspace workspace = null; try { workspace = pWorkspaceFactory.Open(pPropertySet, 0); } catch (Exception ex) { Console.WriteLine("连接Sde时发生错误:" + ex.Message); return null; } return workspace; }
/// <summary> /// creates a sde connection file outfl name of the file sv server ins instance db database ver version /// owner.name method osa or dbms user and password /// </summary> /// <returns>path to connection file</returns> public string createSDEConnFile(string outfl, string sv, string ins, string db, string ver, string method,string user,object pass) { string path = null; //Console.WriteLine(outfl + "\n" + sv + "\n" + ins + "\n" + db + "\n" + ver + "\n" + method + "\n" + user + "\n" + pass); try { string dir = System.IO.Path.GetDirectoryName(outfl); string fname = System.IO.Path.GetFileName(outfl); if (System.IO.Path.HasExtension(fname)) { string ext = System.IO.Path.GetExtension(outfl); if (ext.ToLower() != ".sde") { fname = fname.Replace(ext, ".sde"); } } else { fname = fname + ".sde"; } path = System.IO.Path.Combine(dir, fname); System.IO.FileInfo fInfo = new System.IO.FileInfo(path); if (fInfo.Exists) { fInfo.Delete(); } IWorkspaceFactory2 wksF = new SdeWorkspaceFactoryClass(); IPropertySet propSet = new PropertySetClass(); propSet.SetProperty("SERVER", sv); propSet.SetProperty("INSTANCE", ins); propSet.SetProperty("DATABASE", db); propSet.SetProperty("VERSION", ver); propSet.SetProperty("AUTHENTICATION_MODE", method.ToUpper()); if(!(user == null || user=="" || pass==null || pass.ToString()=="") & method.ToLower()=="dbms") { propSet.SetProperty("USER",user); propSet.SetProperty("PASSWORD",pass); //Console.WriteLine(pass.ToString()); } wksF.Create(dir, fname, propSet, 0); } catch(Exception e) { Console.WriteLine("Error: " + e.ToString()); path = null; } return path; }
//添加字段end public void connectSDE() { ESRI.ArcGIS.esriSystem.IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("server", "42.96.131.137"); propertySet.SetProperty("instance", "sde:oracle11g:orcl");//这个隐藏的很深 propertySet.SetProperty("database", "orcl");//数据库名称 propertySet.SetProperty("user", "sys"); propertySet.SetProperty("password", "iswift638187"); propertySet.SetProperty("version", "SDE.DEFAULT"); SdeWorkspaceFactory sdeWkspFact = new SdeWorkspaceFactoryClass(); IFeatureWorkspace pFeaWksp = (IFeatureWorkspace)sdeWkspFact.Open(propertySet, 0); IFeatureClass pFCRoads = pFeaWksp.OpenFeatureClass("point"); IFeatureLayer pFLRoads = new FeatureLayer(); pFLRoads.FeatureClass = pFCRoads; pFLRoads.Name = "点"; ILayer pLayerRoads = pFLRoads as ILayer; Global.mainmap.AddLayer(pLayerRoads); }
/// <summary> /// Creates a SDE version on production database partent version is Project /// </summary> /// <param name="outfl">connection file</param> /// <param name="versname">verison name</param> /// <param name="sdeConn">sdeConneciton</param> /// <returns>new conneciton file</returns> public string createSDEVersion(string outfl,string versname,string sdeConn) { string x = null; try { IWorkspace wks; IWorkspaceFactory wsFact; IPropertySet propSet; string parentVersion = null; if (sdeConn == null) { propSet = getProjectPS(); wsFact = new SdeWorkspaceFactoryClass(); wks = wsFact.Open(propSet, 0); } else { Console.WriteLine("Creating version connection location = " + sdeConn); wks = OpenWorkSpace(sdeConn); propSet = wks.ConnectionProperties; wsFact = wks.WorkspaceFactory; } IVersionedWorkspace3 vwks = wks as IVersionedWorkspace3; IEnumVersionInfo eVinfo = vwks.Versions; IVersionInfo vinfo = eVinfo.Next(); IVersion version = null; while (vinfo != null) { string vName = vinfo.VersionName; if (vName.ToLower().EndsWith(propSet.GetProperty("VERSION").ToString().ToLower())) { parentVersion = vName; version = vwks.FindVersion(vName); break; } vinfo = eVinfo.Next(); } if (versionExist(versname, sdeConn)) { Console.WriteLine("Error: Version " + versname + " already exists"); return null; } IVersion cversion = version.CreateVersion(versname); IWorkspace wks2 = (IWorkspace)cversion; wsFact.Create(System.IO.Path.GetDirectoryName(outfl), System.IO.Path.GetFileName(outfl), wks2.ConnectionProperties,0); x = outfl; } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); x = null; } return x; }
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 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; } }
/// <summary> /// synchronizes all 2 way child replicas with parent given sde conneciton string /// </summary> /// <param name="sdeConnection">connection string</param> /// <param name="syncConflicts">conflict type</param> /// <param name="syncDirection">sync direction</param> /// <returns>true if success otherwise false</returns> public bool SynchronizeReplica(string sdeConnection, esriReplicationAgentReconcilePolicy syncConflicts,esriReplicaSynchronizeDirection syncDirection) { Console.WriteLine("Starting Synchronization"); bool x = true; try { IWorkspace cwks = OpenWorkSpace(sdeConnection); if (cwks != null) { IGeoDataServer childGDS = new GeoDataServerClass(); IGeoDataServerInit childGDSInit = (IGeoDataServerInit)childGDS; childGDSInit.InitWithWorkspace(cwks); IReplicationAgent replicationAgent = new ReplicationAgentClass(); //need to get parent GDS and replica names IGPReplicas childReps = childGDS.Replicas; IGPReplica childRep = null; IGPReplicas parentReps = null; IGPReplica parentRep = null; IGeoDataServer parentGDS = new GeoDataServerClass(); IWorkspaceFactory2 pWksFact = null; IWorkspace pwks = null; IGeoDataServerInit parentGDSInit = null; bool repFind = false; string msg = ""; string pConnectStr = null; if (childReps.Count == 0) { Console.WriteLine("Could not find any Replicas in local database"); } for (int i = 0; i < childReps.Count; i++) { childRep = childReps.get_Element(i); if (childRep.Role == esriReplicaRole.esriReplicaRoleChild) { repFind = false; msg = ""; pConnectStr = childRep.SibConnectionString; Console.WriteLine(pConnectStr); pWksFact = new SdeWorkspaceFactoryClass(); pwks = pWksFact.OpenFromString(pConnectStr, 0); parentGDSInit = (IGeoDataServerInit)parentGDS; parentGDSInit.InitWithWorkspace(pwks); parentReps = parentGDS.Replicas; if (parentReps.Count == 0) { Console.WriteLine("Could not find any replicas in Parent database"); } for (int j = 0; j < parentReps.Count; j++) { parentRep = parentReps.get_Element(j); if (j == 0) { msg = parentRep.Name; } else { msg = msg + "; " + parentRep.Name; } //use ubound string[] prNameArr, crNameArr; prNameArr = parentRep.Name.Split(new char[] { '.' }); crNameArr = childRep.Name.Split(new char[] { '.' }); string prName, crName; prName = prNameArr[prNameArr.GetUpperBound(0)]; crName = crNameArr[crNameArr.GetUpperBound(0)]; Console.WriteLine("prName = " + prName + "\ncrName = " + crName); if (prName.ToLower() == crName.ToLower()) { try { Console.WriteLine("\tSynchronizing with parent database"); replicationAgent.SynchronizeReplica(childGDS, parentGDS, childRep, parentRep, syncConflicts, syncDirection, false); x = true; repFind = true; break; } catch (Exception e) { Console.WriteLine("Error: Could not sync Replica " + childRep.Name + " error message = " + e.ToString()); x = false; break; } } } if (!repFind) { Console.WriteLine("\tCould not find Recplica named " + childRep.Name + " in Parent Database.\n\tValid names in parent include: " + msg); x = false; } } else { Console.WriteLine("\t" + childRep.Name + " is a parent replica. Skipping Synchronization."); } } } else { Console.WriteLine("Workspace not valid"); x = false; } } catch (Exception e) { Console.WriteLine(e.ToString()); x = false; } return x; }
/// <summary> /// Open a table class from an SDE Workspace /// </summary> /// <param name="conFilePath">string path to the SDE connection file</param> /// <param name="tabName">Table class name</param> /// <param name="fdsName">Optional name of feature dataset</param> /// <param name="versionName">Optional version name, defaults to the version specified by the connection file</param> /// <returns></returns> public static ITable openTableFromSDE(string conFilePath, string tabName, string fdsName = "", string versionName = "") { ITable table = null; IWorkspaceFactory factory = new SdeWorkspaceFactoryClass(); IPropertySet props = factory.ReadConnectionPropertiesFromFile(conFilePath); if (versionName != "") { props.SetProperty("VERSION", versionName); } IWorkspace workspace = factory.Open(props, 0); IFeatureWorkspace featWorkspace = (IFeatureWorkspace)workspace; if (fdsName != "") { IFeatureDataset featdataset = featWorkspace.OpenFeatureDataset(fdsName); IFeatureWorkspace datasetWorkspace = (IFeatureWorkspace)featdataset.Workspace; table = datasetWorkspace.OpenTable(tabName); } else { table = featWorkspace.OpenTable(tabName); } return table; }
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(); }
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; } }
void Button5Click(object sender, EventArgs e) { string waarde, SQL, naam, status, map; int nummer; IEnvelope env; IActiveView pActiveView; IPoint punt; IMap pMap; PropertySet pPropertySet; IWorkspaceFactory pSdeFact; IWorkspace pWorkspace; IFeatureWorkspace pFeatureWorkspace; IFeatureLayer pFeatureLayer; IFeatureClass pFeatureClass; ESRI.ArcGIS.Catalog.IGxLayer pGxLayer; ESRI.ArcGIS.Catalog.IGxFile pGxFile; double minx, miny, maxx, maxy; if (listBox1.SelectedIndex == -1) { MessageBox.Show("Selecteer eerst een dataset uit de lijst.", "Foutmelding"); return; } try { this.Cursor = Cursors.WaitCursor; naam = ""; status = ""; nummer = listBox1.SelectedIndex; waarde = listBox1.Items[nummer].ToString(); SQL = "SELECT NAAM, FYSIEKE_LOCATIE FROM DATASET WHERE DATASET_TITEL = '" + waarde + "'"; mycommand = new OleDbCommand (SQL, mydb); OleDbDataReader myreader = mycommand.ExecuteReader(); try { while (myreader.Read()) { naam = myreader.GetString(0).ToString(); status = myreader.GetString(1).ToString(); } } catch (Exception ex){ MessageBox.Show (ex.ToString(), "Foutmelding"); this.Cursor = Cursors.Default; } finally { myreader.Close(); } map = layer + status + "\\" + naam + ".lyr"; try{ if (System.IO.File.Exists(@map)) { pActiveView = hookHelper.ActiveView; env = pActiveView.Extent; punt = env.LowerLeft; minx = punt.X; miny = punt.Y; punt = env.UpperRight; maxx = punt.X; maxy = punt.Y; pGxLayer = new ESRI.ArcGIS.Catalog.GxLayerClass(); pGxFile = (ESRI.ArcGIS.Catalog.IGxFile)pGxLayer; pGxFile.Path = map; pMap = hookHelper.FocusMap; pMap.AddLayer(pGxLayer.Layer); pActiveView.Extent.XMin = minx; pActiveView.Extent.XMax = maxx; pActiveView.Extent.YMin = miny; pActiveView.Extent.YMax = maxy; pActiveView.Refresh(); this.Cursor = Cursors.Default; } else { MessageBox.Show("Er is geen opmaakbestand van de geselecteerde dataset aanwezig. De dataset wordt nu zonder opmaak uit de geo-database gehaald.","Informatie"); SQL = "SELECT ALT_TITEL FROM DATASET WHERE DATASET_TITEL = '" + waarde + "'"; mycommand = new OleDbCommand (SQL, mydb); OleDbDataReader myreader1 = mycommand.ExecuteReader(); try { while (myreader1.Read()) { pActiveView = hookHelper.ActiveView; pPropertySet = new PropertySetClass(); pPropertySet.SetProperty("SERVER", "chios"); pPropertySet.SetProperty("INSTANCE", "5151"); pPropertySet.SetProperty("DATABASE", ""); pPropertySet.SetProperty("USER", "gisuser"); pPropertySet.SetProperty("PASSWORD", "zonnetje"); pPropertySet.SetProperty("VERSION", "SDE.DEFAULT"); env = pActiveView.Extent; punt = env.LowerLeft; minx = punt.X; miny = punt.Y; punt = env.UpperRight; maxx = punt.X; maxy = punt.Y; pSdeFact = new SdeWorkspaceFactoryClass(); pWorkspace = pSdeFact.Open(pPropertySet, 0); pFeatureWorkspace = pWorkspace as IFeatureWorkspace; pFeatureClass = pFeatureWorkspace.OpenFeatureClass(myreader1.GetString(0).ToString()); pMap = hookHelper.FocusMap; pFeatureLayer = new FeatureLayerClass(); pFeatureLayer.FeatureClass = pFeatureClass; pFeatureLayer.Name = pFeatureClass.AliasName; pFeatureLayer.Visible = true; pFeatureLayer.Selectable = true; pMap.AddLayer(pFeatureLayer); pActiveView.Extent.XMin = minx; pActiveView.Extent.XMax = maxx; pActiveView.Extent.YMin = miny; pActiveView.Extent.YMax = maxy; pActiveView.Refresh(); this.Cursor = Cursors.Default; } } catch (Exception ex){ MessageBox.Show (ex.ToString(), "Foutmelding"); this.Cursor = Cursors.Default; } finally { myreader.Close(); } } } catch (Exception ex) { MessageBox.Show (ex.ToString(), "Foutmelding"); this.Cursor = Cursors.Default; } } catch { MessageBox.Show("Er is geen PDF voor deze dataset aanwezig.", "Foutmelding"); this.Cursor = Cursors.Default; } }
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; }
/// <summary> /// gets all version on a sde database /// </summary> /// <param name="sdeConn">sde connection</param> /// <returns>array of version info</returns> public IVersionInfo[] getVersionsInfo(string sdeConn) { List<IVersionInfo> vers = new List<IVersionInfo>(); IWorkspace wks; if (sdeConn != null) { wks = OpenWorkSpace(sdeConn); } else { IPropertySet propSet = getProjectPS(); IWorkspaceFactory wkFact = new SdeWorkspaceFactoryClass(); wks = wkFact.Open(propSet, 0); } IVersionedWorkspace3 vwks = wks as IVersionedWorkspace3; IEnumVersionInfo vEnumInfo = vwks.Versions; IVersionInfo vInfo = vEnumInfo.Next(); while (vInfo != null) { vers.Add(vInfo); vInfo = vEnumInfo.Next(); } return vers.ToArray(); }
private IPropertySet getProjectPS() { IWorkspaceFactory wksF = new SdeWorkspaceFactoryClass(); IPropertySet propSet = new PropertySetClass(); propSet.SetProperty("SERVER", server); propSet.SetProperty("INSTANCE", instance); propSet.SetProperty("DATABASE", database); propSet.SetProperty("VERSION", pVersion); propSet.SetProperty("AUTHENTICATION_MODE", mode); propSet.SetProperty("USER", user); propSet.SetProperty("PASSWORD", pass); return propSet; }
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 }