读取选中项目信息
重点是DTE 接口的使用,MSDN的描述是:DTE 接口Visual Studio 自动化对象模型中的顶级对象。强大到当前开发环境中任何属性可以拿到例如:当前打开的文档集合,解决方案下的项目信息……剩下自己看,传送门
下面是代码示例:
var dte = (DTE)GetService(typeof(SDTE)); /// <summary> /// 获取选中项目的信息 /// </summary> /// <param name="dte"></param> /// <returns></returns> public static SelectedProject GetSelectedProjectInfo(this DTE dte) { var selectedItems = dte.SelectedItems; var projectName = (from SelectedItem item in selectedItems select item.Name).ToList(); if (!selectedItems.MultiSelect && selectedItems.Count == 1) { var selectProject = selectedItems.Item(projectName.First()); var projectFileList = (from ProjectItem projectItem in selectProject.Project.ProjectItems where projectItem.Name.EndsWith(".cs") select Path.GetFileNameWithoutExtension(projectItem.Name)).ToList(); return new SelectedProject(selectProject.Project.FullName, selectProject.Project, projectFileList); } return null; }
读取实体配置信息
配置存放两点信息:数据库连接、类文件模版,同时我们约定存放在项目根目录下。如下图
那么,剩下就是XML的基本获取处理了。__entity.xml的模版在源码里,可自行拷贝去需要使用的项目,以下是代码示例:
private void AutoBuildEntityEvent(object sender, EventArgs e) { var autoBuildEntityContent = new AutoBuildEntityContent (); //读取选中项目下的配置信息 var entityXmlModel = new EntityXml(autoBuildEntityContent.SelectedProject.EntityXmlPath); entityXmlModel.Load(); autoBuildEntityContent.EntityXml = entityXmlModel; new MainForm(autoBuildEntityContent).ShowDialog(); } public class EntityXml { private readonly string _path; public EntityXml(string path) { _path = path; } public string ConnString { get; private set; } public string EntityTemplate { get; private set; } /// <summary> /// 读取_entity.xml /// </summary> /// <returns></returns> public EntityXml Load() { var xml = new XmlDocument(); xml.Load(_path); var autoEntityNode = xml.SelectSingleNode("AutoEntity"); if (autoEntityNode != null) { var connStringNode = autoEntityNode.SelectSingleNode("ConnString"); if (connStringNode != null) { ConnString = connStringNode.InnerText; } var templatesNodes = autoEntityNode.SelectSingleNode("Template"); if (templatesNodes != null) { EntityTemplate = templatesNodes.InnerText; } } return this; } }
读取物理表
查询当前数据库的表集合,传给窗体做列表展示,直接上代码:
/// <summary> /// 物理表 /// </summary> public class DbTable { public string TableName { get; private set; } public List<TableColumn> Columns { get; set; } private readonly string _conn; public DbTable(string conn) { _conn = conn; } public DbTable(string tableName, List<TableColumn> columns) { TableName = tableName; Columns = columns; } public List<string> QueryTablesName() { var result = SqlHelper.Query(_conn, @"SELECT name FROM sysobjects WHERE xtype IN ( 'u','v' ); "); return (from DataRow row in result.Rows select row[0].ToString()).ToList(); } public List<DbTable> GetTables(List<string> tablesName) { if (!tablesName.Any()) return new List<DbTable>(); var t = new TableColumn(_conn); var columns = t.QueryColumn(tablesName); return columns.GroupBy(a => a.TableName).Select(a => new DbTable(a.Key, a.ToList())).ToList(); } }