PDF.NET框架操作——工具应用(一)
时间:2014-05-16 21:07:34
收藏:0
阅读:546
PDF.NET是个开源的项目其解决UI层(WinForm / Web)控件数据绑定、映射与查询; BLL层实体对象查询(OQL);DAL层SQL语句和.NET数据访问代码映射(查看 SQL-MAP 原理);由于其工具是VB语言开发,个人将他翻成C#版本,仅供学习和交流,对于初学者和C#初学者有一定能够帮助;有不足之处大家尽管拍砖,下面进入正题:
- 程序界面
- 大致思路
通过数据库连接查询所有表名——》根据表中列名、描述及字段类型生成实体类对应的属性——》根据项目需求实体类样式生成文件
- 所需控件
LookUpEdit(记录历史输入数据)、TextEdit(输入密码以掩码的形式展现)、SimpleButton(触发操作)、ButtonEdit(选择文档输出目录)、GridControl(数据展示的容器)、ProgressBar(操作进度条)
- 后台代码实现
1 public partial class runForm : Form 2 { 3 public runForm() 4 { 5 InitializeComponent(); 6 Load += new EventHandler(runForm_Load); 7 8 //锁定窗口大小 9 this.FormBorderStyle = FormBorderStyle.FixedDialog; 10 11 //显示查询区域 12 this.gvTable.ShowFindPanel(); 13 } 14 15 void runForm_Load(object sender, EventArgs e) 16 { 17 connFile = GetConfigFilePath("UserHistory.txt"); 18 19 //标准格式 "Data Source=10.10.198.242;Initial Catalog=mesbj;User ID=sa;Password=sa 20 //数据库地址赋值 21 DataConnect dc = GetConnect(connFile); 22 if (dc == null) 23 return; 24 lueDataSource.Text = dc.dataSource; 25 lueDataBase.Text = dc.dataBase; 26 lueUser.Text = dc.user; 27 txtPassWord.Text = dc.passWord; 28 29 lueDataSource.Properties.DataSource = sourcelst; 30 lueDataBase.Properties.DataSource = baselst; 31 lueUser.Properties.DataSource = userlst; 32 } 33 34 /// <summary> 35 /// 读取配置文件给界面复制默认值 36 /// </summary> 37 /// <returns></returns> 38 private DataConnect GetConnect(string connPath) 39 { 40 DataConnect dc = new DataConnect(); 41 string strcon = File.ReadAllText(connPath, Encoding.UTF8); 42 string[] str = strcon.Split(‘;‘); 43 for (int i = 0; i < str.Count(); i++) 44 { 45 switch (i) 46 { 47 case 0: 48 dc.dataSource = GetConfig(str[i].Split(‘=‘)[1], i); 49 break; 50 case 1: 51 dc.dataBase = GetConfig(str[i].Split(‘=‘)[1], i); 52 break; 53 case 2: 54 dc.user = GetConfig(str[i].Split(‘=‘)[1], i); 55 break; 56 case 3: 57 dc.passWord = GetConfig(str[i].Split(‘=‘)[1], i); 58 break; 59 case 4: 60 OutputPath.Text = GetConfig(str[i].Split(‘=‘)[1], i); 61 break; 62 default: 63 break; 64 } 65 } 66 return dc; 67 } 68 69 /// <summary> 70 /// 数据库连接配置文件 71 /// </summary> 72 private string connFile { set; get; } 73 74 /// <summary> 75 /// 数据库地址 76 /// </summary> 77 private List<string> sourcelst { set; get; } 78 79 /// <summary> 80 /// 数据库名称 81 /// </summary> 82 private List<string> baselst { set; get; } 83 84 /// <summary> 85 /// 用户 86 /// </summary> 87 private List<string> userlst { set; get; } 88 89 /// <summary> 90 /// 所有表名 91 /// </summary> 92 private List<string> tables { set; get; } 93 94 /// <summary> 95 /// 当前选择表名 96 /// </summary> 97 private string scttable { set; get; } 98 99 /// <summary> 100 /// 读取=号最后一个值 101 /// </summary> 102 /// <param name="str"></param> 103 /// <returns></returns> 104 private string GetConfig(string str, int i) 105 { 106 string[] con = str.Split(‘,‘); 107 switch (i) 108 { 109 case 0: 110 sourcelst = new List<string>(); 111 sourcelst.AddRange(con.ToArray()); 112 break; 113 case 1: 114 baselst = new List<string>(); 115 baselst.AddRange(con.ToArray()); 116 break; 117 case 2: 118 userlst = new List<string>(); 119 userlst.AddRange(con.ToArray()); 120 break; 121 default: 122 break; 123 } 124 //获取最后一项作为默认值 125 string config = con[con.Count() - 1]; 126 return config; 127 } 128 129 /// <summary> 130 /// 读取文件路径 131 /// </summary> 132 /// <param name="fileName"></param> 133 /// <returns></returns> 134 private string GetConfigFilePath(string fileName) 135 { 136 string currenctDir = AppDomain.CurrentDomain.BaseDirectory;//存放路径 137 string configFile = System.IO.Path.Combine(currenctDir, fileName); 138 return configFile; 139 } 140 141 /// <summary> 142 /// lookupEdit 添加控制 143 /// </summary> 144 /// <param name="sender"></param> 145 /// <param name="e"></param> 146 private void lueDataSource_ProcessNewValue(object sender, ProcessNewValueEventArgs e) 147 { 148 LookUpEdit lue = sender as LookUpEdit; 149 AddDataSurce(lue); 150 } 151 152 /// <summary> 153 /// LookUpEdit 输入字段添加赋值 154 /// </summary> 155 /// <param name="lue">输入字段</param> 156 private void AddDataSurce(LookUpEdit lue) 157 { 158 string value = lue.Text; 159 if (string.IsNullOrEmpty(value)) 160 return; 161 (lue.Properties.DataSource as List<string>).Add(value); 162 } 163 164 /// <summary> 165 /// 连接 166 /// </summary> 167 /// <param name="sender"></param> 168 /// <param name="e"></param> 169 private void btnConnect_Click(object sender, EventArgs e) 170 { 171 DataConnect dc = new DataConnect(); 172 dc.dataSource = lueDataSource.Text; 173 dc.dataBase = lueDataBase.Text; 174 dc.user = lueUser.Text; 175 dc.passWord = txtPassWord.Text; 176 177 SqlHelper sl = new SqlHelper(dc); 178 179 DataTable dt = SqlHelper.GetTables(@"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ‘BASE TABLE‘"); 180 181 List<TableName> lst = new List<TableName>(); 182 183 tables = new List<string>(); 184 foreach (DataRow item in dt.Rows) 185 { 186 tables.Add(item[0].ToString()); 187 lst.Add(new TableName() { name = item[0].ToString() }); 188 } 189 gcTable.DataSource = lst; 190 191 WriteConninfo(); 192 } 193 194 /// <summary> 195 /// 写入连接配置 196 /// </summary> 197 private void WriteConninfo() 198 { 199 //数据库地址 200 string strconn = @"Data Source=" + WriteConninfo(lueDataSource, sourcelst) + ";Initial Catalog=" + WriteConninfo(lueDataBase, baselst) + 201 ";User ID=" + WriteConninfo(lueUser, userlst) + ";Password=" + txtPassWord.Text + ";OutputPath=" + OutputPath.Text; 202 File.WriteAllText(connFile, strconn); 203 } 204 205 private string WriteConninfo(LookUpEdit lup, List<string> lst) 206 { 207 lst = new List<string>(); 208 lst = lup.Properties.DataSource as List<string>; 209 if (lst.Contains(lup.Text)) 210 { 211 lst.Remove(lup.Text); 212 lst.Add(lup.Text); 213 } 214 string conn = ""; 215 foreach (string item in lst) 216 { 217 conn = conn + item + ","; 218 } 219 return conn.TrimEnd(‘,‘); 220 } 221 222 /// <summary> 223 /// table 表选中事件,查询表中所有字段 224 /// </summary> 225 /// <param name="sender"></param> 226 /// <param name="e"></param> 227 private void gvTable_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) 228 { 229 TableName dv = gvTable.GetRow(e.FocusedRowHandle) as TableName; 230 if (dv == null) 231 return; 232 string table = dv.name; 233 dv.template = true; 234 235 //DataTable dt = SqlHelper.GetTables("Select name from syscolumns Where ID=OBJECT_ID(‘" + table + "‘) "); 236 //gcColumn.DataSource = dt; 237 } 238 239 /// <summary> 240 /// 选择输出目录 241 /// </summary> 242 /// <param name="sender"></param> 243 /// <param name="e"></param> 244 private void OutputPath_ButtonClick(object sender, ButtonPressedEventArgs e) 245 { 246 FolderBrowserDialog fbd = new FolderBrowserDialog(); 247 248 if (fbd.ShowDialog() == DialogResult.OK) 249 { 250 this.OutputPath.Text = fbd.SelectedPath; ; 251 } 252 } 253 254 /// <summary> 255 /// 实体类生成 256 /// </summary> 257 /// <param name="sender"></param> 258 /// <param name="e"></param> 259 private void btnMakeFile_Click(object sender, EventArgs e) 260 { 261 if (tables == null || tables.Count == 0) 262 { 263 MessageBox.Show("请先连接数据库", "实体类生成器"); 264 return; 265 } 266 267 if (!Directory.Exists(OutputPath.Text)) 268 { 269 MessageBox.Show("指定的代码输出目录" + OutputPath.Text + "不存在,请在属性窗口选择有效的路径。", "实体类生成器"); 270 return; 271 } 272 273 if (rbtnSelectOneTable.Checked) 274 { 275 tables = new List<string>(); 276 foreach (TableName item in gvTable.DataSource as List<TableName>) 277 { 278 if (item.template) 279 { 280 tables.Add(item.name); 281 } 282 } 283 } 284 285 PrgBarMakeFile.Maximum = tables.Count; 286 287 txtMakeLog.Text = ""; 288 if (string.IsNullOrEmpty(OutputPath.Text)) 289 { 290 MessageBox.Show("OutputPath路径不能为空!", "实体类生成器"); 291 return; 292 } 293 294 int count = 0; 295 foreach (string item in tables) 296 { 297 count++; 298 txtMakeLog.AppendText("正在生成第" + count + " 个实体类文件: " + OutputPath.Text + "\\" + item + ".cs" + "\r\n"); 299 PrgBarMakeFile.Value = count; 300 CreatModelCode(item); 301 } 302 MessageBox.Show("生成 " + count + " 个实体类文件!", "实体类生成器"); 303 304 WriteConninfo(); 305 } 306 307 /// <summary> 308 /// 创建实体类文件内容 309 /// </summary> 310 /// <param name="tableNam"></param> 311 private void CreatModelCode(string tableName) 312 { 313 //表结构主键 314 string primaryKey = ""; 315 //列名集合 316 string propertyNames = ""; 317 318 DataTable dt = SqlHelper.GetTables("select top 0 * from " + tableName); 319 320 if (dt.PrimaryKey != null && dt.PrimaryKey.Count() > 0) 321 { 322 primaryKey = dt.PrimaryKey[0].ToString(); 323 } 324 325 foreach (DataColumn item in dt.Columns) 326 { 327 propertyNames = propertyNames + ",\"" + item.ColumnName + "\""; 328 } 329 propertyNames = propertyNames.TrimStart(‘,‘); 330 331 StringBuilder sb = new StringBuilder(); 332 sb.AppendLine("using System;"); 333 //转化配置处理 334 sb.AppendLine("using System.Collections.Generic;"); 335 sb.AppendLine("using System.Text;"); 336 337 sb.AppendLine(); 338 339 //转化配置处理 340 sb.AppendLine("namespace Com.Wisdom.VO"); 341 sb.AppendLine("{"); 342 343 sb.AppendLine(" [Serializable()]"); 344 345 //继承基类,转化配置处理 346 sb.AppendLine(" public partial class " + tableName + " : WsdGenericDto"); 347 348 sb.AppendLine(" {"); 349 350 //构造函数 351 sb.AppendLine(" public " + tableName + "()"); 352 sb.AppendLine(" {"); 353 sb.AppendLine(" TableName = " + "\"" + tableName + "\";"); 354 sb.AppendLine(" EntityMap=EntityMapType.Table;"); 355 sb.AppendLine(" //IdentityName = \"标识字段名\";"); 356 sb.AppendLine(); 357 sb.AppendLine(" //PrimaryKeys.Add(\"主键字段名\")"); 358 359 sb.AppendLine(" PrimaryKeys.Add(" + "\"" + primaryKey + "\")"); 360 sb.AppendLine(); 361 sb.AppendLine(" }"); 362 363 sb.AppendLine(" protected override void SetFieldNames()"); 364 sb.AppendLine(" {"); 365 sb.AppendLine(" PropertyNames = new string[] { " + propertyNames + "};"); 366 sb.AppendLine(" }"); 367 368 sb.AppendLine(); 369 sb.AppendLine(); 370 371 foreach (DataColumn item in dt.Columns) 372 { 373 sb.AppendLine(); 374 sb.AppendLine(" /// <summary>"); 375 sb.AppendLine(" /// " + GetDescribe(tableName, item.ColumnName)); 376 sb.AppendLine(" /// </summary>"); 377 sb.AppendLine(" public " + GetDataType(item) + item.ColumnName); 378 sb.AppendLine(" {"); 379 sb.AppendLine(" get{return getProperty<" + GetDataType(item) + ">(\"" + item.ColumnName + "\");}"); 380 sb.AppendLine(" set{setProperty(\"" + item.ColumnName + "\",value " + GetMaxValue(item) + ");}"); 381 sb.AppendLine(" }"); 382 } 383 384 sb.AppendLine(); 385 sb.AppendLine(); 386 387 sb.AppendLine(" }"); 388 389 sb.AppendLine("}"); 390 391 string configFile = OutputPath.Text + "\\" + tableName + ".cs"; 392 File.WriteAllText(configFile, sb.ToString()); 393 } 394 395 /// <summary> 396 /// 获取列名描述 397 /// </summary> 398 /// <param name="table"></param> 399 /// <param name="column"></param> 400 /// <returns></returns> 401 private string GetDescribe(string table, string column) 402 { 403 string describe = ""; 404 DataTable dt = SqlHelper.GetTables(@"SELECT value FROM ::fn_listextendedproperty(NULL,‘user‘,‘dbo‘,‘table‘,‘" + table + "\‘" + ",‘column‘,NULL) WHERE objname=‘" + column + "\‘"); 405 if (dt != null && dt.Rows != null && dt.Rows.Count > 0) 406 { 407 describe = dt.Rows[0].ItemArray[0].ToString(); 408 } 409 return describe; 410 } 411 412 /// <summary> 413 /// 根据表中最大值,处理 414 /// </summary> 415 /// <param name="column"></param> 416 /// <returns></returns> 417 private string GetMaxValue(DataColumn column) 418 { 419 if (column.MaxLength > 0) 420 { 421 return "," + column.MaxLength.ToString(); 422 } 423 else return ""; 424 } 425 426 /// <summary> 427 /// 判断表中列是否为空处理,范围属性类型 428 /// </summary> 429 /// <param name="column"></param> 430 /// <returns></returns> 431 private string GetDataType(DataColumn column) 432 { 433 if (column.AllowDBNull && column.DataType.IsValueType) 434 { 435 return column.DataType + "? ";//表字段为空,类属性中添加? 436 } 437 else 438 { 439 return column.DataType.ToString() + " "; 440 } 441 } 442 }
SqlHelper代码
1 public class SqlHelper 2 { 3 private static string strconn; 4 5 public SqlHelper(DataConnect dc) 6 { 7 strconn = @"data source=" + dc.dataSource + ";database=" + dc.dataBase + ";user id=" + dc.user + ";password=" + dc.passWord; 8 } 9 10 public static DataTable GetTables(string sql) 11 { 12 DataTable dt = new DataTable(); 13 try 14 { 15 using (SqlConnection cnn = new SqlConnection(strconn)) 16 { 17 cnn.Open(); 18 using (SqlCommand cmd = cnn.CreateCommand()) 19 { 20 cmd.CommandText = sql;//执行sql 21 DataSet dataset = new DataSet(); 22 SqlDataAdapter dapter = new SqlDataAdapter(cmd); 23 dapter.FillSchema(dataset, SchemaType.Source); 24 dapter.Fill(dataset);//将dataset添加到SqlDataAdapter容器中 25 dt = dataset.Tables[0]; 26 } 27 } 28 } 29 catch (Exception e) 30 { 31 MessageBox.Show(e.Message); 32 } 33 return dt; 34 } 35 }
评论(0)