PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Src/XCoder/FrmMain.cs

#
C# | 570 lines | 442 code | 85 blank | 43 comment | 75 complexity | 0eb7c8366f1ff13634159b7e7fb3fc2a MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Net;
  9. using System.Reflection;
  10. using System.Threading;
  11. using System.Windows.Forms;
  12. using System.Xml;
  13. using XCode.DataAccessLayer;
  14. using XTemplate.Templating;
  15. namespace XCoder
  16. {
  17. public partial class FrmMain : Form
  18. {
  19. #region 属性
  20. /// <summary>
  21. /// 配置
  22. /// </summary>
  23. public static XConfig Config { get { return XConfig.Current; } }
  24. private XCoder _Coder;
  25. /// <summary>生成器</summary>
  26. public XCoder Coder
  27. {
  28. get { return _Coder ?? (_Coder = new XCoder(Config)); }
  29. set { _Coder = value; }
  30. }
  31. #endregion
  32. #region 界面初始化
  33. public FrmMain()
  34. {
  35. InitializeComponent();
  36. AutoLoadTables(Config.ConnName);
  37. FileSource.CheckTemplate();
  38. }
  39. private void FrmMain_Shown(object sender, EventArgs e)
  40. {
  41. Text = "新生命代码生成器 V" + FileVersion;
  42. Template.BaseClassName = typeof(XCoderBase).FullName;
  43. }
  44. private static String _FileVersion;
  45. /// <summary>
  46. /// 文件版本
  47. /// </summary>
  48. public static String FileVersion
  49. {
  50. get
  51. {
  52. if (String.IsNullOrEmpty(_FileVersion))
  53. {
  54. Assembly asm = Assembly.GetExecutingAssembly();
  55. AssemblyFileVersionAttribute av = Attribute.GetCustomAttribute(asm, typeof(AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute;
  56. if (av != null) _FileVersion = av.Version;
  57. if (String.IsNullOrEmpty(_FileVersion)) _FileVersion = "1.0";
  58. }
  59. return _FileVersion;
  60. }
  61. }
  62. private void FrmMain_Load(object sender, EventArgs e)
  63. {
  64. //ConnectionStringSettingsCollection conns = ConfigurationManager.ConnectionStrings;
  65. //if (conns != null && conns.Count > 0)
  66. //{
  67. // foreach (ConnectionStringSettings item in conns)
  68. // {
  69. // if (item.Name.Equals("LocalSqlServer", StringComparison.OrdinalIgnoreCase)) continue;
  70. // cbConn.Items.Add(item.Name);
  71. // }
  72. // cbConn.SelectedIndex = 0;
  73. //}
  74. List<String> list = new List<String>();
  75. foreach (String item in DAL.ConnStrs.Keys)
  76. {
  77. list.Add(item);
  78. }
  79. Conns = list;
  80. BindTemplate(cb_Template);
  81. LoadConfig();
  82. ThreadPool.QueueUserWorkItem(AutoDetectDatabase);
  83. ThreadPool.QueueUserWorkItem(UpdateArticles);
  84. }
  85. /// <summary>
  86. /// 自动检测数据库,主要针对MSSQL
  87. /// </summary>
  88. /// <param name="state"></param>
  89. void AutoDetectDatabase(Object state)
  90. {
  91. List<String> list = new List<String>();
  92. // 加上本机
  93. DAL.AddConnStr("localhost", "server=.;Integrated Security=SSPI;Database=master", null, "sqlclient");
  94. foreach (String item in DAL.ConnStrs.Keys)
  95. {
  96. if (!String.IsNullOrEmpty(DAL.ConnStrs[item].ConnectionString)) list.Add(item);
  97. }
  98. String[] sysdbnames = new String[] { "master", "tempdb", "model", "msdb" };
  99. List<String> names = new List<String>();
  100. foreach (String item in list)
  101. {
  102. try
  103. {
  104. DAL dal = DAL.Create(item);
  105. DataSet ds = null;
  106. // 列出所有数据库
  107. if (dal.DbType == DatabaseType.SqlServer)
  108. {
  109. if (dal.Db.ServerVersion.StartsWith("08"))
  110. ds = dal.Select("SELECT name FROM sysdatabases", "");
  111. else
  112. ds = dal.Select("SELECT name FROM sys.databases", "");
  113. }
  114. else
  115. continue;
  116. DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
  117. builder.ConnectionString = dal.ConnStr;
  118. // 统计库名
  119. foreach (DataRow dr in ds.Tables[0].Rows)
  120. {
  121. String dbname = dr[0].ToString();
  122. if (Array.IndexOf(sysdbnames, dbname) >= 0) continue;
  123. String connName = String.Format("{0}_{1}", item, dbname);
  124. builder["Database"] = dbname;
  125. DAL.AddConnStr(connName, builder.ToString(), null, "sql2000");
  126. try
  127. {
  128. String ver = dal.Db.ServerVersion;
  129. names.Add(connName);
  130. }
  131. catch
  132. {
  133. if (DAL.ConnStrs.ContainsKey(connName)) DAL.ConnStrs.Remove(connName);
  134. }
  135. }
  136. }
  137. catch
  138. {
  139. if (item == "localhost") DAL.ConnStrs.Remove("localhost");
  140. }
  141. }
  142. if (DAL.ConnStrs.ContainsKey("localhost")) DAL.ConnStrs.Remove("localhost");
  143. if (list.Contains("localhost")) list.Remove("localhost");
  144. if (names != null && names.Count > 0)
  145. {
  146. list.AddRange(names);
  147. Conns = list;
  148. }
  149. }
  150. /// <summary>
  151. /// 连接字符串
  152. /// </summary>
  153. List<String> Conns = null;
  154. /// <summary>
  155. /// 模版绑定
  156. /// </summary>
  157. public void BindTemplate(ComboBox cb)
  158. {
  159. String TemplatePath = XCoder.TemplatePath;
  160. cb.Items.Clear();
  161. if (!Directory.Exists(TemplatePath))
  162. {
  163. MessageBox.Show("模版目录 " + TemplatePath + " 不存在,正在初始化!");
  164. //Thread.Sleep(3000);
  165. }
  166. if (!Directory.Exists(TemplatePath))
  167. {
  168. //Directory.CreateDirectory(TemplatePath);
  169. MessageBox.Show("模版目录 " + TemplatePath + " 不存在,请先添加模版");
  170. return;
  171. }
  172. DirectoryInfo dir = new DirectoryInfo(TemplatePath);
  173. DirectoryInfo[] dirs = dir.GetDirectories();
  174. List<String> dirs2 = new List<string>();
  175. foreach (DirectoryInfo d in dirs)
  176. {
  177. if (d.Name != "bin" && d.Name != "obj" && d.Name != "Properties") dirs2.Add(d.Name);
  178. }
  179. cb.DataSource = dirs2;
  180. cb.DisplayMember = "value";
  181. cb.Update();
  182. }
  183. private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
  184. {
  185. SaveConfig();
  186. }
  187. #endregion
  188. #region 连接
  189. private void bt_Connection_Click(object sender, EventArgs e)
  190. {
  191. SaveConfig();
  192. if (bt_Connection.Text == "连接")
  193. {
  194. cb_Table.Items.Clear();
  195. Coder = null;
  196. cb_Table.DataSource = Coder.Tables;
  197. cb_Table.DisplayMember = "Name";
  198. cb_Table.ValueMember = "Name";
  199. groupBox1.Enabled = false;
  200. groupBox2.Enabled = true;
  201. bt_Connection.Text = "断开";
  202. }
  203. else
  204. {
  205. cb_Table.DataSource = null;
  206. cb_Table.Items.Clear();
  207. groupBox1.Enabled = true;
  208. groupBox2.Enabled = false;
  209. bt_Connection.Text = "连接";
  210. }
  211. }
  212. void AutoLoadTables(String name)
  213. {
  214. if (String.IsNullOrEmpty(name)) return;
  215. // 异步加载
  216. ThreadPool.QueueUserWorkItem(delegate(Object state)
  217. {
  218. try
  219. {
  220. IList<XTable> tables = DAL.Create(name).Tables;
  221. }
  222. catch (Exception ex)
  223. {
  224. //MessageBox.Show(ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  225. //lb_Status.Text = ex.Message;
  226. }
  227. });
  228. }
  229. #endregion
  230. #region 生成
  231. Stopwatch sw = new Stopwatch();
  232. private void bt_GenTable_Click(object sender, EventArgs e)
  233. {
  234. SaveConfig();
  235. if (cb_Template.SelectedValue == null || cb_Table.SelectedValue == null) return;
  236. sw.Reset();
  237. sw.Start();
  238. try
  239. {
  240. String[] ss = Coder.Render(cb_Table.Text);
  241. richTextBox1.Text = ss[0];
  242. }
  243. catch (Exception ex)
  244. {
  245. MessageBox.Show(ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  246. }
  247. sw.Stop();
  248. lb_Status.Text = "生成 " + cb_Table.Text + " 完成!耗时:" + sw.Elapsed.ToString();
  249. }
  250. private void bt_GenAll_Click(object sender, EventArgs e)
  251. {
  252. SaveConfig();
  253. if (cb_Template.SelectedValue == null || cb_Table.Items.Count < 1) return;
  254. IList<XTable> tables = Coder.Tables;
  255. if (tables == null || tables.Count < 1) return;
  256. pg_Process.Minimum = 0;
  257. pg_Process.Maximum = tables.Count;
  258. pg_Process.Step = 1;
  259. pg_Process.Value = pg_Process.Minimum;
  260. List<String> param = new List<string>();
  261. //param.Add(cb_Template.Text);
  262. //param.Add(txt_OutPath.Text);
  263. //for (int i = 0; i < cb_Table.Items.Count; i++)
  264. //{
  265. // param.Add(cb_Table.GetItemText(cb_Table.Items[i]));
  266. //}
  267. foreach (XTable item in tables)
  268. {
  269. param.Add(item.Name);
  270. }
  271. bt_GenAll.Enabled = false;
  272. if (!bw.IsBusy)
  273. {
  274. sw.Reset();
  275. sw.Start();
  276. bw.RunWorkerAsync(param);
  277. }
  278. else
  279. bw.CancelAsync();
  280. }
  281. private void bw_DoWork(object sender, DoWorkEventArgs e)
  282. {
  283. List<String> param = e.Argument as List<String>;
  284. int i = 1;
  285. foreach (String tableName in param)
  286. {
  287. try
  288. {
  289. Coder.Render(tableName);
  290. }
  291. catch (Exception ex)
  292. {
  293. bw.ReportProgress(i++, "出错:" + ex.ToString());
  294. break;
  295. }
  296. bw.ReportProgress(i++, "已生成:" + tableName);
  297. if (bw.CancellationPending) break;
  298. }
  299. }
  300. private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
  301. {
  302. pg_Process.Value = e.ProgressPercentage;
  303. proc_percent.Text = (int)(100 * pg_Process.Value / pg_Process.Maximum) + "%";
  304. lb_Status.Text = e.UserState.ToString();
  305. if (lb_Status.Text.StartsWith("出错")) MessageBox.Show(lb_Status.Text, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  306. }
  307. private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  308. {
  309. pg_Process.Value = pg_Process.Maximum;
  310. proc_percent.Text = (int)(100 * pg_Process.Value / pg_Process.Maximum) + "%";
  311. Coder = null;
  312. sw.Stop();
  313. lb_Status.Text = "生成 " + cb_Table.Items.Count + " 个类完成!耗时:" + sw.Elapsed.ToString();
  314. bt_GenAll.Enabled = true;
  315. }
  316. #endregion
  317. #region 加载保存
  318. public void LoadConfig()
  319. {
  320. if (!String.IsNullOrEmpty(Config.ConnName))
  321. {
  322. if (String.IsNullOrEmpty(Config.EntityConnName)) Config.EntityConnName = Config.ConnName;
  323. if (String.IsNullOrEmpty(Config.NameSpace)) Config.NameSpace = Config.ConnName;
  324. if (String.IsNullOrEmpty(Config.OutputPath)) Config.OutputPath = Config.ConnName;
  325. }
  326. cbConn.Text = Config.ConnName;
  327. cb_Template.Text = Config.TemplateName;
  328. txt_OutPath.Text = Config.OutputPath;
  329. txt_NameSpace.Text = Config.NameSpace;
  330. txt_ConnName.Text = Config.EntityConnName;
  331. txtPrefix.Text = Config.Prefix;
  332. checkBox1.Checked = Config.AutoCutPrefix;
  333. checkBox2.Checked = Config.AutoFixWord;
  334. checkBox3.Checked = Config.UseCNFileName;
  335. checkBox5.Checked = Config.UseHeadTemplate;
  336. richTextBox2.Text = Config.HeadTemplate;
  337. checkBox4.Checked = Config.Debug;
  338. }
  339. public void SaveConfig()
  340. {
  341. if (!String.IsNullOrEmpty(Config.ConnName))
  342. {
  343. if (String.IsNullOrEmpty(Config.EntityConnName)) Config.EntityConnName = Config.ConnName;
  344. if (String.IsNullOrEmpty(Config.NameSpace)) Config.NameSpace = Config.ConnName;
  345. if (String.IsNullOrEmpty(Config.OutputPath)) Config.OutputPath = Config.ConnName;
  346. }
  347. Config.ConnName = cbConn.Text;
  348. Config.TemplateName = cb_Template.Text;
  349. Config.OutputPath = txt_OutPath.Text;
  350. Config.NameSpace = txt_NameSpace.Text;
  351. Config.EntityConnName = txt_ConnName.Text;
  352. Config.Prefix = txtPrefix.Text;
  353. Config.AutoCutPrefix = checkBox1.Checked;
  354. Config.AutoFixWord = checkBox2.Checked;
  355. Config.UseCNFileName = checkBox3.Checked;
  356. Config.UseHeadTemplate = checkBox5.Checked;
  357. Config.HeadTemplate = richTextBox2.Text;
  358. Config.Debug = checkBox4.Checked;
  359. Config.Save();
  360. }
  361. #endregion
  362. #region 导出映射文件
  363. private void button1_Click(object sender, EventArgs e)
  364. {
  365. IList<XTable> tables = DAL.Create(Config.ConnName).Tables;
  366. if (tables == null || tables.Count < 1) return;
  367. foreach (XTable table in tables)
  368. {
  369. XCoder.AddWord(table.Name, table.Description);
  370. foreach (XField field in table.Fields)
  371. {
  372. XCoder.AddWord(field.Name, field.Description);
  373. }
  374. }
  375. MessageBox.Show("完成!", this.Text);
  376. }
  377. #endregion
  378. #region 自动化
  379. private void timer1_Tick(object sender, EventArgs e)
  380. {
  381. if (Conns != null)
  382. {
  383. String str = cbConn.Text;
  384. cbConn.DataSource = Conns;
  385. cbConn.DisplayMember = "value";
  386. cbConn.Update();
  387. Conns = null;
  388. if (!String.IsNullOrEmpty(str)) cbConn.Text = str;
  389. }
  390. }
  391. private void cbConn_SelectedIndexChanged(object sender, EventArgs e)
  392. {
  393. AutoLoadTables(cbConn.Text);
  394. if (String.IsNullOrEmpty(cb_Template.Text)) cb_Template.Text = cbConn.Text;
  395. if (String.IsNullOrEmpty(txt_OutPath.Text)) txt_OutPath.Text = cbConn.Text;
  396. if (String.IsNullOrEmpty(txt_NameSpace.Text)) txt_NameSpace.Text = cbConn.Text;
  397. }
  398. #endregion
  399. #region 附加信息
  400. private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  401. {
  402. Control control = sender as Control;
  403. if (control == null) return;
  404. String url = String.Empty;
  405. if (control.Tag != null) url = control.Tag.ToString();
  406. if (String.IsNullOrEmpty(url)) url = control.Text;
  407. if (String.IsNullOrEmpty(url)) return;
  408. Process.Start(url);
  409. }
  410. private void label3_Click(object sender, EventArgs e)
  411. {
  412. Clipboard.SetData("10193406", null);
  413. MessageBox.Show("QQ群号已复制到剪切板!", "提示");
  414. }
  415. List<Article> articles = new List<Article>();
  416. void UpdateArticles(Object state)
  417. {
  418. try
  419. {
  420. String url = "http://www.cnblogs.com/nnhy/rss";
  421. WebClient client = new WebClient();
  422. Stream stream = client.OpenRead(url);
  423. XmlDocument doc = new XmlDocument();
  424. doc.Load(stream);
  425. XmlNodeList nodes = doc.SelectNodes(@"//item");
  426. if (nodes != null && nodes.Count > 0)
  427. {
  428. foreach (XmlNode item in nodes)
  429. {
  430. Article entity = new Article();
  431. entity.Title = item.SelectSingleNode("title").InnerText;
  432. entity.Link = item.SelectSingleNode("link").InnerText;
  433. entity.Description = item.SelectSingleNode("description").InnerText;
  434. try
  435. {
  436. entity.PubDate = Convert.ToDateTime(item.SelectSingleNode("pubDate").InnerText);
  437. }
  438. catch { }
  439. #region 强制弹出
  440. if (entity.PubDate > DateTime.MinValue)
  441. {
  442. Int32 h = (Int32)(DateTime.Now - entity.PubDate).TotalHours;
  443. if (h < 24 * 30)
  444. {
  445. Random rnd = new Random((Int32)DateTime.Now.Ticks);
  446. // 时间越久,h越大,随机数为0的可能性就越小,弹出的可能性就越小
  447. // 一小时之内,是50%的可能性
  448. if (rnd.Next(0, h + 1) == 0)
  449. {
  450. Process.Start(entity.Link);
  451. }
  452. }
  453. }
  454. #endregion
  455. articles.Add(entity);
  456. }
  457. }
  458. }
  459. catch (Exception ex)
  460. {
  461. MessageBox.Show(ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  462. }
  463. }
  464. Int32 articleIndex = 0;
  465. private void timer2_Tick(object sender, EventArgs e)
  466. {
  467. if (articles != null && articles.Count > 0)
  468. {
  469. if (articleIndex >= articles.Count) articleIndex = 0;
  470. Article entity = articles[articleIndex];
  471. linkLabel1.Text = entity.Title;
  472. linkLabel1.Tag = entity.Link;
  473. articleIndex++;
  474. }
  475. }
  476. class Article
  477. {
  478. public String Title;
  479. public String Link;
  480. public DateTime PubDate;
  481. public String Description;
  482. }
  483. #endregion
  484. }
  485. }