PDF.NET框架操作——工具应用(一)

时间:2023-03-10 06:27:41
PDF.NET框架操作——工具应用(一)

PDF.NET是个开源的项目其解决UI层(WinForm / Web)控件数据绑定、映射与查询; BLL层实体对象查询(OQL);DAL层SQL语句和.NET数据访问代码映射(查看  SQL-MAP 原理);由于其工具是VB语言开发,个人将他翻成C#版本,仅供学习和交流,对于初学者和C#初学者有一定能够帮助;有不足之处大家尽管拍砖,下面进入正题:

  1. 程序界面

PDF.NET框架操作——工具应用(一)

  • 大致思路

通过数据库连接查询所有表名——》根据表中列名、描述及字段类型生成实体类对应的属性——》根据项目需求实体类样式生成文件

  • 所需控件

LookUpEdit(记录历史输入数据)、TextEdit(输入密码以掩码的形式展现)、SimpleButton(触发操作)、ButtonEdit(选择文档输出目录)、GridControl(数据展示的容器)、ProgressBar(操作进度条)

  • 后台代码实现
     public partial class runForm : Form
{
public runForm()
{
InitializeComponent();
Load += new EventHandler(runForm_Load); //锁定窗口大小
this.FormBorderStyle = FormBorderStyle.FixedDialog; //显示查询区域
this.gvTable.ShowFindPanel();
} void runForm_Load(object sender, EventArgs e)
{
connFile = GetConfigFilePath("UserHistory.txt"); //标准格式 "Data Source=10.10.198.242;Initial Catalog=mesbj;User ID=sa;Password=sa
//数据库地址赋值
DataConnect dc = GetConnect(connFile);
if (dc == null)
return;
lueDataSource.Text = dc.dataSource;
lueDataBase.Text = dc.dataBase;
lueUser.Text = dc.user;
txtPassWord.Text = dc.passWord; lueDataSource.Properties.DataSource = sourcelst;
lueDataBase.Properties.DataSource = baselst;
lueUser.Properties.DataSource = userlst;
} /// <summary>
/// 读取配置文件给界面复制默认值
/// </summary>
/// <returns></returns>
private DataConnect GetConnect(string connPath)
{
DataConnect dc = new DataConnect();
string strcon = File.ReadAllText(connPath, Encoding.UTF8);
string[] str = strcon.Split(';');
for (int i = ; i < str.Count(); i++)
{
switch (i)
{
case :
dc.dataSource = GetConfig(str[i].Split('=')[], i);
break;
case :
dc.dataBase = GetConfig(str[i].Split('=')[], i);
break;
case :
dc.user = GetConfig(str[i].Split('=')[], i);
break;
case :
dc.passWord = GetConfig(str[i].Split('=')[], i);
break;
case :
OutputPath.Text = GetConfig(str[i].Split('=')[], i);
break;
default:
break;
}
}
return dc;
} /// <summary>
/// 数据库连接配置文件
/// </summary>
private string connFile { set; get; } /// <summary>
/// 数据库地址
/// </summary>
private List<string> sourcelst { set; get; } /// <summary>
/// 数据库名称
/// </summary>
private List<string> baselst { set; get; } /// <summary>
/// 用户
/// </summary>
private List<string> userlst { set; get; } /// <summary>
/// 所有表名
/// </summary>
private List<string> tables { set; get; } /// <summary>
/// 当前选择表名
/// </summary>
private string scttable { set; get; } /// <summary>
/// 读取=号最后一个值
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string GetConfig(string str, int i)
{
string[] con = str.Split(',');
switch (i)
{
case :
sourcelst = new List<string>();
sourcelst.AddRange(con.ToArray());
break;
case :
baselst = new List<string>();
baselst.AddRange(con.ToArray());
break;
case :
userlst = new List<string>();
userlst.AddRange(con.ToArray());
break;
default:
break;
}
//获取最后一项作为默认值
string config = con[con.Count() - ];
return config;
} /// <summary>
/// 读取文件路径
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private string GetConfigFilePath(string fileName)
{
string currenctDir = AppDomain.CurrentDomain.BaseDirectory;//存放路径
string configFile = System.IO.Path.Combine(currenctDir, fileName);
return configFile;
} /// <summary>
/// lookupEdit 添加控制
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lueDataSource_ProcessNewValue(object sender, ProcessNewValueEventArgs e)
{
LookUpEdit lue = sender as LookUpEdit;
AddDataSurce(lue);
} /// <summary>
/// LookUpEdit 输入字段添加赋值
/// </summary>
/// <param name="lue">输入字段</param>
private void AddDataSurce(LookUpEdit lue)
{
string value = lue.Text;
if (string.IsNullOrEmpty(value))
return;
(lue.Properties.DataSource as List<string>).Add(value);
} /// <summary>
/// 连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnConnect_Click(object sender, EventArgs e)
{
DataConnect dc = new DataConnect();
dc.dataSource = lueDataSource.Text;
dc.dataBase = lueDataBase.Text;
dc.user = lueUser.Text;
dc.passWord = txtPassWord.Text; SqlHelper sl = new SqlHelper(dc); DataTable dt = SqlHelper.GetTables(@"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'"); List<TableName> lst = new List<TableName>(); tables = new List<string>();
foreach (DataRow item in dt.Rows)
{
tables.Add(item[].ToString());
lst.Add(new TableName() { name = item[].ToString() });
}
gcTable.DataSource = lst; WriteConninfo();
} /// <summary>
/// 写入连接配置
/// </summary>
private void WriteConninfo()
{
//数据库地址
string strconn = @"Data Source=" + WriteConninfo(lueDataSource, sourcelst) + ";Initial Catalog=" + WriteConninfo(lueDataBase, baselst) +
";User ID=" + WriteConninfo(lueUser, userlst) + ";Password=" + txtPassWord.Text + ";OutputPath=" + OutputPath.Text;
File.WriteAllText(connFile, strconn);
} private string WriteConninfo(LookUpEdit lup, List<string> lst)
{
lst = new List<string>();
lst = lup.Properties.DataSource as List<string>;
if (lst.Contains(lup.Text))
{
lst.Remove(lup.Text);
lst.Add(lup.Text);
}
string conn = "";
foreach (string item in lst)
{
conn = conn + item + ",";
}
return conn.TrimEnd(',');
} /// <summary>
/// table 表选中事件,查询表中所有字段
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void gvTable_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
TableName dv = gvTable.GetRow(e.FocusedRowHandle) as TableName;
if (dv == null)
return;
string table = dv.name;
dv.template = true; //DataTable dt = SqlHelper.GetTables("Select name from syscolumns Where ID=OBJECT_ID('" + table + "') ");
//gcColumn.DataSource = dt;
} /// <summary>
/// 选择输出目录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OutputPath_ButtonClick(object sender, ButtonPressedEventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK)
{
this.OutputPath.Text = fbd.SelectedPath; ;
}
} /// <summary>
/// 实体类生成
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMakeFile_Click(object sender, EventArgs e)
{
if (tables == null || tables.Count == )
{
MessageBox.Show("请先连接数据库", "实体类生成器");
return;
} if (!Directory.Exists(OutputPath.Text))
{
MessageBox.Show("指定的代码输出目录" + OutputPath.Text + "不存在,请在属性窗口选择有效的路径。", "实体类生成器");
return;
} if (rbtnSelectOneTable.Checked)
{
tables = new List<string>();
foreach (TableName item in gvTable.DataSource as List<TableName>)
{
if (item.template)
{
tables.Add(item.name);
}
}
} PrgBarMakeFile.Maximum = tables.Count; txtMakeLog.Text = "";
if (string.IsNullOrEmpty(OutputPath.Text))
{
MessageBox.Show("OutputPath路径不能为空!", "实体类生成器");
return;
} int count = ;
foreach (string item in tables)
{
count++;
txtMakeLog.AppendText("正在生成第" + count + " 个实体类文件: " + OutputPath.Text + "\\" + item + ".cs" + "\r\n");
PrgBarMakeFile.Value = count;
CreatModelCode(item);
}
MessageBox.Show("生成 " + count + " 个实体类文件!", "实体类生成器"); WriteConninfo();
} /// <summary>
/// 创建实体类文件内容
/// </summary>
/// <param name="tableNam"></param>
private void CreatModelCode(string tableName)
{
//表结构主键
string primaryKey = "";
//列名集合
string propertyNames = ""; DataTable dt = SqlHelper.GetTables("select top 0 * from " + tableName); if (dt.PrimaryKey != null && dt.PrimaryKey.Count() > )
{
primaryKey = dt.PrimaryKey[].ToString();
} foreach (DataColumn item in dt.Columns)
{
propertyNames = propertyNames + ",\"" + item.ColumnName + "\"";
}
propertyNames = propertyNames.TrimStart(','); StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
//转化配置处理
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Text;"); sb.AppendLine(); //转化配置处理
sb.AppendLine("namespace Com.Wisdom.VO");
sb.AppendLine("{"); sb.AppendLine(" [Serializable()]"); //继承基类,转化配置处理
sb.AppendLine(" public partial class " + tableName + " : WsdGenericDto"); sb.AppendLine(" {"); //构造函数
sb.AppendLine(" public " + tableName + "()");
sb.AppendLine(" {");
sb.AppendLine(" TableName = " + "\"" + tableName + "\";");
sb.AppendLine(" EntityMap=EntityMapType.Table;");
sb.AppendLine(" //IdentityName = \"标识字段名\";");
sb.AppendLine();
sb.AppendLine(" //PrimaryKeys.Add(\"主键字段名\")"); sb.AppendLine(" PrimaryKeys.Add(" + "\"" + primaryKey + "\")");
sb.AppendLine();
sb.AppendLine(" }"); sb.AppendLine(" protected override void SetFieldNames()");
sb.AppendLine(" {");
sb.AppendLine(" PropertyNames = new string[] { " + propertyNames + "};");
sb.AppendLine(" }"); sb.AppendLine();
sb.AppendLine(); foreach (DataColumn item in dt.Columns)
{
sb.AppendLine();
sb.AppendLine(" /// <summary>");
sb.AppendLine(" /// " + GetDescribe(tableName, item.ColumnName));
sb.AppendLine(" /// </summary>");
sb.AppendLine(" public " + GetDataType(item) + item.ColumnName);
sb.AppendLine(" {");
sb.AppendLine(" get{return getProperty<" + GetDataType(item) + ">(\"" + item.ColumnName + "\");}");
sb.AppendLine(" set{setProperty(\"" + item.ColumnName + "\",value " + GetMaxValue(item) + ");}");
sb.AppendLine(" }");
} sb.AppendLine();
sb.AppendLine(); sb.AppendLine(" }"); sb.AppendLine("}"); string configFile = OutputPath.Text + "\\" + tableName + ".cs";
File.WriteAllText(configFile, sb.ToString());
} /// <summary>
/// 获取列名描述
/// </summary>
/// <param name="table"></param>
/// <param name="column"></param>
/// <returns></returns>
private string GetDescribe(string table, string column)
{
string describe = "";
DataTable dt = SqlHelper.GetTables(@"SELECT value FROM ::fn_listextendedproperty(NULL,'user','dbo','table','" + table + "\'" + ",'column',NULL) WHERE objname='" + column + "\'");
if (dt != null && dt.Rows != null && dt.Rows.Count > )
{
describe = dt.Rows[].ItemArray[].ToString();
}
return describe;
} /// <summary>
/// 根据表中最大值,处理
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
private string GetMaxValue(DataColumn column)
{
if (column.MaxLength > )
{
return "," + column.MaxLength.ToString();
}
else return "";
} /// <summary>
/// 判断表中列是否为空处理,范围属性类型
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
private string GetDataType(DataColumn column)
{
if (column.AllowDBNull && column.DataType.IsValueType)
{
return column.DataType + "? ";//表字段为空,类属性中添加?
}
else
{
return column.DataType.ToString() + " ";
}
}
}

SqlHelper代码

     public class SqlHelper
{
private static string strconn; public SqlHelper(DataConnect dc)
{
strconn = @"data source=" + dc.dataSource + ";database=" + dc.dataBase + ";user id=" + dc.user + ";password=" + dc.passWord;
} public static DataTable GetTables(string sql)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection cnn = new SqlConnection(strconn))
{
cnn.Open();
using (SqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = sql;//执行sql
DataSet dataset = new DataSet();
SqlDataAdapter dapter = new SqlDataAdapter(cmd);
dapter.FillSchema(dataset, SchemaType.Source);
dapter.Fill(dataset);//将dataset添加到SqlDataAdapter容器中
dt = dataset.Tables[];
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return dt;
}
}