using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using CommLibrary;
using Model;
using DAL;
using System.IO;
using System.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using System.Threading;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Xml;//ReWriteCSPROJ(string Path,string Content)
namespace WebBuilder
{
public partial class Form1 : Form
{
DataTable Dt = null;
DataTable ValuesDt = null;
DataTable RelDt = null;
FormProcess FormPro;
Thread _Thread;
IList<Model.FromRelation> formrellist = null;
private DbConnInfo dbConnInfo = new DbConnInfo();
private string currDBName;
string _Current_Table = "";
ISQLHelper CDBHelper;
public Form1()
{
InitializeComponent();
}
string folder = string.Empty;
string ExcelFile = string.Empty;
private void button4_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = this.openFileDialog1.FileName;
ExcelFile = this.openFileDialog1.FileName;
}
}
private void SimpleRun()
{
string ErrPage = string.Empty;
try
{
Monitor.Enter(this);//锁定,保持同步
FormPro.progressBar1.Value = 0;
FormPro.CurrProcessTable.Text = "开始生成项目....";
currDBName = this._CB_DB.Text;
CDataBase _HostDataBase = new CDataBase();
//IList<TemplateTable> _ListTemplateTable = new List<TemplateTable>();
IList<TemplateTable> _BuildListTemplateTable = new List<TemplateTable>();
TemplateTable _TempTable = null;
IList<Columns> _ColsList = null;
IList<Relation> retRelation = null;
IList<Relation> retConvertRelation = null;
IList<TemplateTable> HasTemplateTable = CDBHelper.getTable(currDBName.Trim());
_HostDataBase.DbName = currDBName.Trim();
DataTable ColumnsDt = null;
DataTable RelationDt = null;
if (dbConnInfo.DbClient == Model.DbType.Sqlite)
{
RelationDt = new DataTable();
RelationDt.Columns.Add("主表名", typeof(string));
RelationDt.Columns.Add("主键列名", typeof(string));
RelationDt.Columns.Add("外键表名称", typeof(string));
RelationDt.Columns.Add("外键列名", typeof(string));
RelationDt.Columns.Add("级联更新", typeof(bool));
RelationDt.Columns.Add("级联删除", typeof(bool));
DataTable tempDt = null;
DataRow tempirow = null;
for (int i = 0; i < HasTemplateTable.Count; i++)
{
_Current_Table = HasTemplateTable[i].TableName.ToString();
tempDt = CDBHelper.getRelationTable(_Current_Table);
if (tempDt != null && tempDt.Rows.Count > 0)
{
foreach (DataRow reader in tempDt.Rows)
{
tempirow = RelationDt.NewRow();
tempirow["主表名"] = _Current_Table;
tempirow["主键列名"] = reader["from"].ToString();
tempirow["外键表名称"] = reader["to"].ToString();
tempirow["外键列名"] = reader["table"].ToString();
tempirow["级联更新"] = reader["on_update"].ToString() == "NO ACTION" ? false : true;
tempirow["级联删除"] = reader["on_delete"].ToString() == "NO ACTION" ? false : true;
RelationDt.Rows.Add(tempirow);
}
}
}
for (int i = 0; i < HasTemplateTable.Count; i++)
{
_Current_Table = HasTemplateTable[i].TableName.ToString();
ColumnsDt = CDBHelper.getColumnsTable(_Current_Table);
_ColsList = CDBHelper.getColumns(ColumnsDt, _Current_Table);
retRelation = CDBHelper.getRelation(RelationDt, _Current_Table);
retConvertRelation = CDBHelper.getConverRelation(RelationDt, _Current_Table);
_TempTable = new TemplateTable();
foreach (TemplateTable currTemp in HasTemplateTable)
{
if (currTemp.TableName.Trim() == _Current_Table.Trim())
{
_TempTable = currTemp;
}
}
_TempTable.Cols = _ColsList;
_TempTable.RelRelationList = retRelation;
_TempTable.ChildRelationList = retConvertRelation;
_TempTable.RelRelationConfig = GetRels(_Current_Table, RelDt);
int step = 1;
bool FirstKey = true; //多键取第一个为主键
foreach (Columns tempcols in _ColsList)
{
tempcols.RelRelation = GetColumnsRelation(tempcols.ColumnsName, retRelation);
if (ValuesDt != null)
tempcols.Dicts = GetColumnsDicts(_Current_Table, tempcols.ColumnsName, ValuesDt);
if (FirstKey && tempcols.IsKey)
{
_TempTable.Key = tempcols;
FirstKey = false;
}
if (step == 2)
{
_TempTable.Name = tempcols;
}
if (tempcols.Name.ToLower() == "title")
{
_TempTable.Name = tempcols;
}
if (tempcols.Name.ToLower() == _Current_Table.ToLower() + "name")
{
_TempTable.Name = tempcols;
}
if (tempcols.Name.ToLower() == "name")
{
_TempTable.Name = tempcols;
}
step++;
}
_TempTable.TableName = _Current_Table;
_TempTable.TableType = getTableType(_TempTable.TableName);
//_ListTemplateTable.Add(_TempTable);
_BuildListTemplateTable.Add(_TempTable);
}
}
else
{
ColumnsDt = CDBHelper.getColumnsTable(currDBName);
RelationDt = CDBHelper.getRelationTable(currDBName);
//不生成全部项目时按表选择全出现漏项的情况
//数据表要经过关联关系生成完整项目程序不能直接在选项项目中选择数据表操作
for (int i = 0; i < HasTemplateTable.Count; i++)
{
_Current_Table = HasTemplateTable[i].TableName.ToString();
if (_Current_Table == "sysmenu")
{
}
_ColsList = CDBHelper.getColumns(ColumnsDt, _Current_Table);
retRelation = CDBHelper.getRelation(RelationDt, _Current_Table);
retConvertRelation = CDBHelper.getConverRelation(RelationDt, _Current_Table);
_TempTable = new TemplateTable();
_TempTable = HasTemplateTable[i];
_TempTable.Cols = _ColsList;
_TempTable.RelRelationList = retRelation;
_TempTable.ChildRelationList = retConvertRelation;
_TempTable.RelRelationConfig = GetRels(_Current_Table, RelDt);
int step = 1;
bool FirstKey = true; //多键取第一个为主键
foreach (Columns tempcols in _ColsList)
{
tempcols.RelRelation = GetColumnsRelation(tempcols.ColumnsName, retRelation);
if (ValuesDt != null)
tempcols.Dicts = GetColumnsDicts(_Current_Table, tempcols.ColumnsName, ValuesDt);
if (FirstKey && tempcols.IsKey)
{
_TempTable.Key = tempcols;
FirstKey = false;
}
if (step == 2)
{
_TempTable.Name = tempcols;
}
if (tempcols.Name.ToLower() == "title")
{
_TempTable.Name = tempcols;
}
if (tempcols.Name.ToLower() == _Current_Table.ToLower() + "name")
{
_TempTable.Name = tempcols;
}
if (tempcols.Name.ToLower() == "name")
{
_TempTable.Name = tempcols;
}
step++;
}
_TempTable.TableName = _Current_Table;
_TempTable.TableType = getTableType(_TempTable.TableName);
//_ListTemplateTable.Add(_TempTable);
_BuildListTemplateTable.Add(_TempTable);
}
}
if (ColumnsDt != null && ColumnsDt.Rows.Count > 0)
{
ColumnsDt.Dispose();
}
if (RelationDt != null && RelationDt.Rows.Count > 0)
{
RelationDt.Dispose();
}
//_ListTemplateTable = Computer(_ListTemplateTable);
_BuildListTemplateTable = Computer(_BuildListTemplateTable);
//_HostDataBase.TemplateTable = _ListTemplateTable;
_HostDataBase.TemplateTable = _BuildListTemplateTable;
#region 菜单
//一级菜单
List<TableMenu> Menus = new List<TableMenu>();
TableMenu sub = null;
foreach (DataRow dr in Dt.Rows)
{
sub = new TableMenu();
sub.DefualtTable = dr["一级菜单"].ToString();
sub.MenuName = dr["二级菜单"].ToString();
if (dr["点亮"].ToString() == "是")
{
sub.ShowType = "1";
}
else
{
sub.ShowType = "0";
}
//目录
sub.Dir = dr["目录"].ToString();
//一级菜单 二级菜单 页面 页面类型
sub.FirstMenu = dr["一级菜单"].ToString();
sub.SecMenu = dr["二级菜单"].ToString();
sub.PageName = dr["页面"].ToString();
sub.PageType = dr["页面类型"].ToString();
sub.PageTitle = dr["二级菜单"].ToString();
Menus.Add(sub);
}
#endregion
string bootpath = AppDomain.CurrentDomain.BaseDirectory + @"ypControl\";
string[] fileList = System.IO.Directory.GetFileSystemEntries(bootpath);
TempClass HeaderTempClass = new TempClass();
HeaderTempClass.TemplateStr = string.Empty;
HeaderTempClass.TempNameSpace = textBoxNS.Text.Trim();
HeaderTempClass.TempTable = _TempTable;
HeaderTempClass.HostDataBase = _HostDataBase;
HeaderTempClass.CreateVersion = "";
HeaderTempClass.Menus = Menus;
if (!Directory.Exists(folder + "\\ypControl\\"))
{
Directory.CreateDirectory(folder + "\\ypControl\\");
}
foreach (string filepath in fileList)
{
HeaderTempClass.TemplateStr = File.ReadAllText(filepath, EncodingType.GetEncoding(filepath));
F_WriteStr(VelocityEngineBuilder(HeaderTempClass), folder + "\\ypControl\\" + filepath.Replace(bootpath, string.Empty));
}
IList<WebMarkString> _TempList = new List<WebMarkString>();
bootpath = AppDomain.CurrentDomain.BaseDirectory + @"T\";
fileList = System.IO.Directory.GetFileSystemEntries(bootpath);
WebMarkString Current = null;
foreach (string filepath in fileList)
{
using (StreamReader SR = new StreamReader(filepath, EncodingType.GetEncoding(filepath)))
{
Current = new WebMarkString();
Current.Tag = filepath.Replace(bootpath, string.Empty);
Current.Link = SR.ReadToEnd();
_TempList.Add(Current);
}
}
string cutable = string.Empty;
string[] relTables = null;
//把目录下相应模块中的缺省页面创建出来。
DataView dv = new DataView(Dt);
DataTable dtdirs = dv.ToTable(true, "目录");
DataTable dtnew = new DataTable();
DataTable NewDt = Dt.Copy();
foreach (DataRow drdir in dtdirs.Rows)
{
//找到目录下的模块
dtnew = GetNewTable(NewDt, "目录='" + drdir["目录"].ToString() + "'");
dv = new DataView(dtnew);
DataTable dttables = dv.ToTable(true, "模块");
foreach (DataRow dr in dttables.Rows)
{
DataRow[] copydr = NewDt.Select("目录='" + drdir["目录"].ToString() + "' and 模块='" + dr["模块"].ToString() + "'");
DataRow[] exist = NewDt.Select("目录='" + drdir["目录"].ToString() + "' and 模块='" + dr["模块"].ToString() + "' and 页面类型='List'");
if (exist == null || exist.Length == 0)
{
if (copydr != null && copydr.Length > 0)
{
copydr[0]["页面类型"] = "List";
copydr[0]["页面"] = dr["模块"].ToString() + "List";
CreateNotExsits(copydr[0], _TempList, _BuildListTemplateTable, _HostDataBase, Menus);
}
}
exist = NewDt.Select("目录='" + drdir["目录"].ToString() + "' and 模块='" + dr["模块"].ToString() + "' and 页面类型='Edit'");
if (exist == null || exist.Length == 0)
{
if (copydr != null && copydr.Length > 0)
{
copydr[0]["页面类型"] = "Edit";
copydr[0]["页面"] = dr["模块"].ToString() + "Edit";
CreateNotExsits(copydr[0], _TempList, _BuildListTemplateTable, _HostDataBase, Menus);
}
}
exist = NewDt.Select("目录='" + drdir["目录"].ToString() + "' and 模块='" + dr["模块"].ToString() + "' and 页面类型='Show'");
if (exist == null || exist.Length == 0)
{
if (copydr != null && copydr.Length > 0)
{
copydr[0]["页面类型"] = "Show";
copydr[0]["页面"] = dr["模块"].ToString() + "Show";
CreateNotExsits(copydr[0], _TempList, _BuildListTemplateTable, _HostDataBase, Menus);
}
}
}
}
foreach (DataRow dr in Dt.Rows)
{
//模块 参数 操作页设置字段 查询条件设置字段 数据显示设置字段
cutable = dr["模块"].ToString().Trim();
relTables = dr["包含模块"].ToString().Split(',');
//string cutable = relTables[0];
//if (cutable.Contains("("))
//{
// string[] item = cutable.Split('(');
// cutable = item[0];
//}
_TempTable = new TemplateTable();
for (int i = 0; i < _BuildListTemplateTable.Count; i++)
{
_Current_Table = _BuildListTemplateTable[i].TableName;
if (cutable.Equals(_Current_Table, StringComparison.CurrentCultureIgnoreCase))
{
_TempTable = _BuildListTemplateTable[i];
}
}
string ClassName = dr["页面"].ToString();
if (ClassName.Equals("default", StringComparison.CurrentCultureIgnoreCase))
{
ClassName = "_" + ClassName;
}
string textBoxFloder = dr["目录"].ToString();
if (textBoxFloder.Length >= 1)
{
textBoxFloder = textBoxFloder.Substring(1);
if (textBoxFloder.Length > 1)
{
if (textBoxFloder.EndsWith("/"))
{
textBoxFloder = textBoxFloder.TrimEnd('/');
}
}
textBoxFloder = textBoxFloder.Replace("/", ".");
}
string CodeName = string.Format("{0}.{1}.{2}", textBoxNS.Text.Trim(), textBoxFloder.Trim(), ClassName);
if (string.IsNullOrWhiteSpace(textBoxFloder.Trim()))
{
CodeName = string.Format("{0}.{1}", textBoxNS.Text.Trim(), ClassName);
}
if (dr["目录"].ToString() != "/")
{
}
string CodeNameSpace = string.Format("{0}.{1}", textBoxNS.Text.Trim(), textBoxFloder.Trim());
if (string.IsNullOrWhiteSpace(textBoxFloder.Trim()))
{
CodeNameSpace = textBoxNS.Text.Trim();
}
if (dr["目录"].ToString() != "/")
{
if (!Directory.Exists(folder + "\\" + dr["目录"].ToString()))
{
Directory.CreateDirectory(folder + "\\" + dr["目录"].ToString());
}
}
string HtmlContent = string.Empty;
string CodeContent = string.Empty;
string DesingerCode = string.Empty;
foreach (WebMarkString listitem in _TempList)
{
if (listitem.Tag == dr["页面类型"].ToString().ToLower() + ".aspx")
{
HtmlContent = listitem.Link;
}
if (listitem.Tag == dr["页面类型"].ToString().ToLower() + ".aspx.cs")
{
CodeContent = listitem.Link;
}
if (listitem.Tag == dr["页面类型"].ToString().ToLower() + ".aspx.designer.cs")
{
DesingerCode = listitem.Link;
}
}
string IsView = dr["点亮"].ToString();//点亮
string IfIsView = dr["显示条件"].ToString();//显示条件
string SessionID = dr["SessionID"].ToString();//SessionID
string AddCart = dr["加入购物车"].ToString();//加入购物车
string Orders = dr["下单"].ToString();//下单
string Payment = dr["支付"].ToString();//支付
#region 定制布局
//数据显示设置字段 查询条件设置字段 操作页设置字段
string ListFiledsPath = dr["数据显示设置字段"].ToString();//数据显示设置字段
string SearchFiledsPath = dr["查询条件设置字段"].ToString();//点亮
string OprationFiledsPath = dr["操作页设置字段"].ToString();//点亮
_TempTable.ListFileds = new List<Columns>();
SetFileds(_TempTable.ListFileds, _ColsList, ListFiledsPath);
_TempTable.SearchFileds = new List<Columns>();
SetFileds(_TempTable.SearchFileds, _ColsList, SearchFiledsPath);
_TempTable.OprationFileds = new List<Columns>();
SetFileds(_TempTable.OprationFileds, _ColsList, OprationFiledsPath);
#endregion
TempClass TempClass = new TempClass();
TempClass.TemplateStr = HtmlContent;
TempClass.TempNameSpace = textBoxNS.Text.Trim();
TempClass.TempTable = _TempTable;
TempClass.HostDataBase = _HostDataBase;
TempClass.CreateVersion = "";
TempClass.Menus = Menus;
//点亮 显示条件 SessionID 包含模块 加入购物车 下单 支付
TempClass.RelTables = relTables;
TempClass.CodeNameSpace = CodeNameSpace;
TempClass.ClassName = ClassName;
TempClass.IsView = IsView;
TempClass.IfIsView = IfIsView;
TempClass.SessionID = SessionID;
TempClass.AddCart = AddCart;
TempClass.Orders = Orders;
TempClass.Payment = Payment;
//目录
TempClass.Dir = dr["目录"].ToString();
//一级菜单 二级菜单 页面 页面类型
TempClass.FirstMenu = dr["一级菜单"].ToString();
TempClass.SecMenu = dr["二级菜单"].ToString();
TempClass.PageName = dr["页面"].ToString();
TempClass.PageType = dr["页面类型"].ToString();
TempClass.PageTitle = dr["二级菜单"].ToString();
TempClass.CodeName = CodeName;
//模块 参数 操作页设置字段 查询条件设置字段 数据显示设置字段
TempClass.TableName = dr["模块"].ToString();
TempClass.TableValues = dr["参数"].ToString();
TempClass.EditJson = dr["操作页设置字段"].ToString();
TempClass.ShowJson = dr["查询条件设置字段"].ToString();
TempClass.ListJson = dr["数据显示设置字段"].ToString();
HtmlContent = VelocityEngineBuilder(TempClass);
TempClass.TemplateStr = CodeContent;
CodeContent = VelocityEngineBuilder(TempClass);
TempClass.TemplateStr = DesingerCode;
TempClass.PageDicts=GetPageDicts(dr["目录"].ToString(),dr["页面"].ToString(),dr["模块"].ToString(), ValuesDt);
DesingerCode = VelocityEngineBuilder(TempClass);
F_WriteStr(HtmlContent, folder + "\\" + dr["目录"].ToString() + "\\" + dr["页面"].ToString() + ".aspx");
F_WriteStr(CodeContent, folder + "\\" + dr["目录"].ToString() + "\\" + dr["页面"].ToString() + ".aspx.cs");
F_WriteStr(DesingerCode, folder + "\\" + dr["目录"].ToString() + "\\" + dr["页面"].ToString() + ".aspx.designer.cs");
}
FormPro.CurrProcessTable.Text = "项目成功生成!";
FormPro.progressBar1.Value = 100;
Application.DoEvents();
Thread.Sleep(5);
Process.Start("explorer.exe", folder);
}
catch (Exception err)
{
MessageBox.Show(ErrPage + ";" + err.Message.ToString());
Thread.CurrentThread.Abort();
}
finally
{
Monitor.Exit(this);
_Thread.Abort();
}
}
private List<Dict> GetPageDicts(string Dir,string Page,string TableName, DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
return null;
List<Dict> dicts = null;
Dict itemdict = null;
DataRow[] drs = dt.Select(string.Format("模块='{0}' and 目录='{1}' and 页面='{2}'", TableName, Dir, Page));
if (drs != null && drs.Length > 0)
{
dicts = new List<Dict>();
foreach (DataRow dr in drs)
{
// 模块 字段 参数值 参数名 列表显示 条件 操作权限 作废
itemdict = new Dict();
itemdict.TableName = dr["模块"].ToString();
itemdict.ColumnsName = dr["字段"].ToString();
itemdict.ItemName = dr["参数值"].ToString();
itemdict.ItemValue = dr["参数名"].ToString();
itemdict.ListView = dr["列表显示"].ToString();
itemdict.Condition = dr["条件"].ToString();
itemdict.Opreation = dr["操作权限"].ToString();
itemdict.IsDel = dr["作废"].ToString();
dicts.Add(itemdict);
}
}
return dicts;
}
private void SetFileds(IList<Columns> _SetFileds, IList<Columns> _ColsList, string SetItem)
{
if (string.IsNullOrWhiteSpace(SetItem))
{
_SetFileds = _ColsList;
}
else
{
if (!string.IsNullOrWhiteSpace(SetItem))
{
string[] SetItems = SetItem.Split(';');
foreach (string sI in SetItems)
{
foreach (Columns item in _ColsList)
{
if (sI == item.ColumnsName)
{
_SetFileds.Add(item);
break;
}
}
}
}
else
{
_SetFileds = _ColsList;
}
}
}
private void CreateNotExsits(DataRow dr, IList<WebMarkString> _TempList, IList<TemplateTable> _BuildListTemplateTable, CDataBase _HostDataBase, List<TableMenu> Menus)
{
//模块 参数 操作页设置字段 查询条件设置字段 数据显示设置字段
string cutable = dr["模块"].ToString().Trim();
string[] relTables = dr["包含模块"].ToString().Split(',');
//string cutable = relTables[0];
//if (cutable.Contains("("))
//{
// string[] item = cutable.Split('(');
// cutable = item[0];
//}
TemplateTable _TempTable = new TemplateTable();
for (int i = 0; i < _BuildListTemplateTable.Count; i++)
{
_Current_Table = _BuildListTemplateTable[i].TableName;
if (cutable.Equals(_Current_Table, StringComparison.CurrentCultureIgnoreCase))
{
_TempTable = _BuildListTemplateTable[i];
}
}
string ClassName = dr["页面"].ToString();
if (ClassName.Equals("default", StringComparison.CurrentCultureIgnoreCase))
{
ClassName = "_" + ClassName;
}
string textBoxFloder = dr["目录"].ToString();
if (textBoxFloder.Length >= 1)
{
textBoxFloder = textBoxFloder.Substring(1);
if (textBoxFloder.Length > 1)
{
if (textBoxFloder.EndsWith("/"))
{
textBoxFloder = textBoxFloder.TrimEnd('/');
}
}
textBoxFloder = textBoxFloder.Replace("/", ".");
}
string CodeName = string.Format("{0}.{1}.{2}", textBoxNS.Text.Trim(), textBoxFloder.Trim(), ClassName);
if (string.IsNullOrWhiteSpace(textBoxFloder.Trim()))
{
CodeName = string.Format("{0}.{1}", textBoxNS.Text.Trim(), ClassName);
}
if (dr["目录"].ToString() != "/")
{
}
string CodeNameSpace = string.Format("{0}.{1}", textBoxNS.Text.Trim(), textBoxFloder.Trim());
if (string.IsNullOrWhiteSpace(textBoxFloder.Trim()))
{
CodeNameSpace = textBoxNS.Text.Trim();
}
if (dr["目录"].ToString() != "/")
{
if (!Directory.Exists(folder + "\\" + dr["目录"].ToString()))
{
Directory.CreateDirectory(folder + "\\" + dr["目录"].ToString());
}
}
string HtmlContent = string.Empty;
string CodeContent = string.Empty;
string DesingerCode = string.Empty;
foreach (WebMarkString listitem in _TempList)
{
if (listitem.Tag == dr["页面类型"].ToString().ToLower() + ".aspx")
{
HtmlContent = listitem.Link;
}
if (listitem.Tag == dr["页面类型"].ToString().ToLower() + ".aspx.cs")
{
CodeContent = listitem.Link;
}
if (listitem.Tag == dr["页面类型"].ToString().ToLower() + ".aspx.designer.cs")
{
DesingerCode = listitem.Link;
}
}
string IsView = dr["点亮"].ToString();//点亮
string IfIsView = dr["显示条件"].ToString();//显示条件
string SessionID = dr["SessionID"].ToString();//SessionID
string AddCart = dr["加入购物车"].ToString();//加入购物车
string Orders = dr["下单"].ToString();//下单
string Payment = dr["支付"].ToString();//支付
TempClass TempClass = new TempClass();
TempClass.TemplateStr = HtmlContent;
TempClass.TempNameSpace = textBoxNS.Text.Trim();
TempClass.TempTable = _TempTable;
TempClass.HostDataBase = _HostDataBase;
TempClass.CreateVersion = "";
TempClass.Menus = Menus;
//点亮 显示条件 SessionID 包含模块 加入购物车 下单 支付
TempClass.RelTables = relTables;
TempClass.CodeNameSpace = CodeNameSpace;
TempClass.ClassName = ClassName;
TempClass.IsView = IsView;
TempClass.IfIsView = IfIsView;
TempClass.SessionID = SessionID;
TempClass.AddCart = AddCart;
TempClass.Orders = Orders;
TempClass.Payment = Payment;
//目录
TempClass.Dir = dr["目录"].ToString();
//一级菜单 二级菜单 页面 页面类型
TempClass.FirstMenu = dr["一级菜单"].ToString();
TempClass.SecMenu = dr["二级菜单"].ToString();
TempClass.PageName = dr["页面"].ToString();
TempClass.PageType = dr["页面类型"].ToString();
TempClass.PageTitle = dr["二级菜单"].ToString();
TempClass.CodeName = CodeName;
//模块 参数 操作页设置字段 查询条件设置字段 数据显示设置字段
TempClass.TableName = dr["模块"].ToString();
TempClass.TableValues = dr["参数"].ToString();
TempClass.EditJson = dr["操作页设置字段"].ToString();
TempClass.ShowJson = dr["查询条件设置字段"].ToString();
TempClass.ListJson = dr["数据显示设置字段"].ToString();
TempClass.PageDicts = GetPageDicts(dr["目录"].ToString(), dr["页面"].ToString(), dr["模块"].ToString(), ValuesDt);
HtmlContent = VelocityEngineBuilder(TempClass);
TempClass.TemplateStr = CodeContent;
CodeContent = VelocityEngineBuilder(TempClass);
TempClass.TemplateStr = DesingerCode;
DesingerCode = VelocityEngineBuilder(TempClass);
F_WriteStr(HtmlContent, folder + "\\" + dr["目录"].ToString() + "\\" + dr["页面"].ToString() + ".aspx");
F_WriteStr(CodeContent, folder + "\\" + dr["目录"].ToString() + "\\" + dr["页面"].ToString() + ".aspx.cs");
F_WriteStr(DesingerCode, folder + "\\" + dr["目录"].ToString() + "\\" + dr["页面"].ToString() + ".aspx.designer.cs");
}
private DataTable GetNewTable(DataTable DT, string strCondition)
{
DataTable TempDT = DT.Clone();
DataRow[] Rows = DT.Select(strCondition);
foreach (DataRow DR in Rows)
{
TempDT.ImportRow(DR);
}
return TempDT;
}
private string ReadPath(string path)
{
if (File.Exists(path))
{
using (StreamReader SR = new StreamReader(path, EncodingType.GetEncoding(path)))
{
return SR.ReadToEnd();
}
}
return string.Empty;
}
private void F_WriteStr(string _Text, string _Path)
{
using (StreamWriter SW = new StreamWriter(_Path, false, Encoding.Unicode))
{
//修改日期:2013-6-23
//修改人:解旭朝
//修改原因:SW.WriteLine(_Text);多产生一个最后的空行
//SW.WriteLine(_Text);改为SW.Write(_Text);
SW.Write(_Text);
SW.Flush();
}
}
void btnStartOrPause_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Text == "暂停")
{
if (_Thread.ThreadState == System.Threading.ThreadState.Background || _Thread.ThreadState == System.Threading.ThreadState.Running)
{
_Thread.Suspend();
btn.Text = "继续";
}
}
else
{
if (_Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Suspended.ToString()))
{
_Thread.Resume();
btn.Text = "暂停";
}
}
}
void btnOver_Click(object sender, EventArgs e)
{
if (_Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Suspended.ToString()))
{
_Thread.Resume();
}
if (_Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Background.ToString()) || _Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Running.ToString()))
{
FormPro.btnStartOrPause.Enabled = false;
FormPro.btnOver.Enabled = false;
_Thread.Abort();
}
}
void btnClose_Click(object sender, EventArgs e)
{
if (_Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Suspended.ToString()))
{
_Thread.Resume();
}
if (_Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Background.ToString()) || _Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Running.ToString()))
{
FormPro.btnStartOrPause.Enabled = false;
FormPro.btnOver.Enabled = false;
_Thread.Abort();
FormPro.Close();
FormPro.Dispose();
}
if (_Thread.ThreadState.ToString().Contains(System.Threading.ThreadState.Stopped.ToString()))
{
FormPro.Close();
FormPro.Dispose();
}
}
private void button5_Click(object sender, EventArgs e)
{
}
/// <summary>
/// 模板生成内容
/// </summary>
/// <param name="TemplateStr">模板字符串</param>
/// <returns></returns>
public string VelocityEngineBuilder(TempClass TempClass)
{
VelocityEngine vltEngine = new VelocityEngine();
vltEngine.Init();
VelocityContext vltContext = new VelocityContext();
//得到数据
if (dbConnInfo != null)
{
if (!string.IsNullOrEmpty(this.dbConnInfo.SqlConnStr))
{
vltContext.Put("SqlConnStr", this.dbConnInfo.SqlConnStr.Trim());
}
if (!string.IsNullOrEmpty(this.dbConnInfo.ServerPostion))
{
vltContext.Put("Server", this.dbConnInfo.ServerPostion.Trim());
}
if (!string.IsNullOrEmpty(currDBName))
{
vltContext.Put("Database", currDBName.Trim());
}
if (!string.IsNullOrEmpty(this.dbConnInfo.ServerUser))
{
vltContext.Put("Uid", this.dbConnInfo.ServerUser.Trim());
}
if (!string.IsNullOrEmpty(dbConnInfo.DbType))
{
vltContext.Put("DbType", dbConnInfo.DbType);
}
vltContext.Put("Password", this.dbConnInfo.ServerPwd.Trim());
}
//,IsView, IfIsView, SessionID, AddCart, Orders, Payment
if (TempClass.IsView == "是")
{
vltContext.Put("IsView", 1);
}
else
{
vltContext.Put("IsView", 0);
}
if (TempClass.IfIsView == "是")
{
vltContext.Put("IfIsView", 1);
}
else
{
vltContext.Put("IfIsView", 0);
}
vltContext.Put("SessionID", TempClass.SessionID);
if (TempClass.AddCart == "是")
{
vltContext.Put("AddCart", 1);
}
else
{
vltContext.Put("AddCart", 0);
}
if (TempClass.Orders == "是")
{
vltContext.Put("Orders", 1);
}
else
{
vltContext.Put("Orders", 0);
}
if (TempClass.Payment == "是")
{
vltContext.Put("Payment", 1);
}
else
{
vltContext.Put("Payment", 0);
}
vltContext.Put("PageDicts", TempClass.PageDicts);
//目录
vltContext.Put("Dir", TempClass.Dir);
//一级菜单 二级菜单 页面 页面类型
vltContext.Put("FirstMenu", TempClass.FirstMenu);
vltContext.Put("SecMenu", TempClass.SecMenu);
vltContext.Put("PageName", TempClass.PageName);
vltContext.Put("PageType", TempClass.PageType);
vltContext.Put("PageTitle", TempClass.PageTitle);
vltContext.Put("CodeName", TempClass.CodeName);
vltContext.Put("CodeNameSpace", TempClass.CodeNameSpace);
vltContext.Put("ClassName", TempClass.ClassName);
vltContext.Put("relTables", TempClass.RelTables);
vltContext.Put("Memu", TempClass.Menus);
vltContext.Put("NameSpace", TempClass.TempNameSpace);
vltContext.Put("GoTable", TempClass.TempTable);
vltContext.Put("Table", TempClass.TempTable.TableName);
vltContext.Put("TableNoPoint", TempClass.TempTable.TableNoPoint);
#region 定制布局
vltContext.Put("ListFileds", TempClass.TempTable.ListFileds);
vltContext.Put("SearchFileds", TempClass.TempTable.SearchFileds);
vltContext.Put("OprationFileds", TempClass.TempTable.OprationFileds);
#endregion
//TableName TableValues EditJson ShowJson ListJson
if (TempClass.TempTable.TableName != null)
{
vltContext.Put("SmallTable", TempClass.TempTable.TableName.ToLower());
}
vltContext.Put("host", TempClass.HostDataBase.TemplateTable);
if (TempClass.HostDataBase.TemplateTable != null && TempClass.HostDataBase.TemplateTable.Count > 0)
{
foreach (TemplateTable TemplateTableItem in TempClass.HostDataBase.TemplateTable)
{
vltContext.Put(TemplateTableItem.TableName, TemplateTableItem);
}
}
vltContext.Put("Columns", TempClass.TempTable.Cols);
vltContext.Put("Now", System.DateTime.Now.ToString());
vltContext.Put("Version", TempClass.CreateVersion);
System.IO.StringWriter vltWriter = new System.IO.StringWriter();
vltEngine.Evaluate(vltContext, vltWriter, null, TempClass.TemplateStr);
return vltWriter.GetStringBuilder().ToString();
}
private IList<Rel> GetRels(string TableName, DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
return null;
IList<Rel> Rels = null;
Rel rel = null;
DataRow[] drs = dt.Select(string.Format("模块='{0}' ", TableName));
if (drs != null && drs.Length > 0)
{
Rels = new List<Rel>();
foreach (DataRow dr in drs)
{
//模块 关系模块 显示列 顺序 编辑功能 删除功能
rel = new Rel();
rel.TableName = dr["模块"].ToString();
rel.RelTableName = dr["关系模块"].ToString();
string[] vfs = dr["显示列"].ToString().Split(',');
if (vfs != null)
{
foreach (string it in vfs)
{
rel.ViewFileds.Add(it);
}
}
rel.OrderBy = dr["顺序"].ToString();
rel.CanEdit = dr["编辑功能"].ToString();
rel.CanDelete = dr["删除功能"].ToString();
Rels.Add(rel);
}
}
return Rels;
}
/// <summary>
/// 找到对应的表及字段下的字典值
/// </summary>
/// <param name="TableName"></param>
/// <param name="ColumnsName"></param>
/// <param name="dt"></param>
/// <returns></returns>
private List<Dict> GetColumnsDicts(string TableName, string ColumnsName, DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
return null;
List<Dict> dicts = null;
Dict itemdict = null;
DataRow[] drs = dt.Select(string.Format("模块='{0}' and 字段='{1}'", TableName, ColumnsName));
if (drs != null && drs.Length > 0)
{
dicts = new List<Dict>();
foreach (DataRow dr in drs)
{
// 模块 字段 参数值 参数名 列表显示 条件 操作权限 作废
itemdict = new Dict();
itemdict.TableName = dr["模块"].ToString();
itemdict.ColumnsName = dr["字段"].ToString();
itemdict.ItemName = dr["参数值"].ToString();
itemdict.ItemValue = dr["参数名"].ToString();
itemdict.ListView = dr["列表显示"].ToString();
itemdict.Condition = dr["条件"].ToString();
itemdict.Opreation = dr["操作权限"].ToString();
itemdict.IsDel = dr["作废"].ToString();
dicts.Add(itemdict);
}
}
return dicts;
}
private Relation GetColumnsRelation(string ColumnsName, IList<Relation> rellist)
{
Relation result = null;
foreach (Relation tmp in rellist)
{
if (tmp.CurrFiled.Trim() == ColumnsName.Trim())
{
result = tmp;
}
}
return result;
}
private int getTableType(string TableName)
{
int controltype = 0;
TableName = TableName.ToLower();
if (TableName.Contains("faceback"))
{
controltype = 1;
}
if (TableName.Contains("category"))
{
controltype = 2;
}
return controltype;
}
private Model.DbType CoverDBType(string dbcom)
{
Model.DbType rs = Model.DbType.SQLServer2005;
switch (dbcom)
{
case "SQL Server 2000":
rs = Model.DbType.SQLServer2000;
break;
case "SQL Server 2008":
rs = Model.DbType.SQLServer2008;
break;
case "Oracle":
rs = Model.DbType.Oracle;
break;
case "MySQL":
rs = Model.DbType.MySQL;
break;
case "Access":
rs = Model.DbType.Access;
break;
case "Sqlite":
rs = Model.DbType.Sqlite;
break;
default:
rs = Model.DbType.SQLServer2005;
break;
}
return rs;
}
private IList<Model.FromRelation> findRelationSql(string tablename)
{
IList<Model.FromRelation> rs = null;
try
{
if (formrellist.Count > 0)
{
rs = new List<FromRelation>();
for (int i = 0; i < formrellist.Count; i++)
{
if (formrellist[i].CurrTable == tablename)
{
rs.Add(formrellist[i]);
}
}
}
}
catch
{
}
return rs;
}
public IList<TemplateTable> Computer(IList<TemplateTable> tables)
{
if (tables != null && tables.Count > 0)
{
foreach (TemplateTable it in tables)
{
foreach (Relation rit in it.RelRelationList)
{
if (rit.CurrentTable == it.TableName)
{
rit.CurrentTableE = it;
foreach (Columns col in it.Cols)
{
if (rit.CurrFiled == col.ColumnsName)
{
rit.CurrFiledE = col;
}
}
}
foreach (TemplateTable fit in tables)
{
if (rit.RelationTable == fit.TableName)
{
rit.RelationTableE = fit;
foreach (Columns col in fit.Cols)
{
if (rit.RelatFiled == col.ColumnsName)
{
rit.RelatFiledE = col;
}
}
}
}
}
}
}
return tables;
//_TempTable.Cols = _ColsList;
//_TempTable.RelRelationList = retRelation;
//_TempTable.ChildRelationList = retConvertRelation;
}
private void button1_Click(object sender, EventArgs e)
{
//this.tv.Nodes.Clear();
try
{
FormConnect formConnect = new FormConnect();
string xmlfile = System.IO.Path.GetFullPath(@"conf.xml");
string postion = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/server", ""));
if (formConnect.CombServerPotion.Items.Contains(postion))
{
formConnect.CombServerPotion.Text = postion;
}
else
{
formConnect.CombServerPotion.Items.Add(postion);
formConnect.CombServerPotion.Text = postion;
}
string typestr = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/type", ""));
if (formConnect.CombDbType.Items.Contains(typestr))
{
formConnect.CombDbType.Text = typestr;
}
else
{
formConnect.CombDbType.Items.Add(typestr);
formConnect.CombDbType.Text = typestr;
}
formConnect.CombServerPotion.Text = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/server", ""));
formConnect.txtUser.Text = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/user", ""));
formConnect.txtPassWord.Text = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/password", ""));
formConnect.txtDBName.Text = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/database", ""));
//formConnect.rtbStr.Text = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/sqlconn", ""));
//string ConnType = XmlHelper.Read(xmlfile, "/conf/conntype", "");
//formConnect.txtTemplatePath.Text = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/templatepath", ""));
//if (ConnType == "0")
//{
// formConnect.radioButton1.Checked = true;
//}
//else
//{
// formConnect.radioButton2.Checked = true;
//}
//BuildVersion = StringUtility.ConvetXMLToTxt(XmlHelper.Read(xmlfile, "/conf/version", ""));
if (formConnect.ShowDialog() == DialogResult.OK)
{
currDBName = formConnect.txtDBName.Text;
dbConnInfo.ServerPostion = formConnect.CombServerPotion.Text;
dbConnInfo.ServerType = formConnect.CombDbType.Text;
dbConnInfo.ServerUser = formConnect.txtUser.Text;
dbConnInfo.ServerPwd = formConnect.txtPassWord.Text;
dbConnInfo.DbClient = CoverDBType(formConnect.CombDbType.Text);
dbConnInfo.DbType = formConnect.CombDbType.Text.Trim();
//dbConnInfo.SqlConnStr = formConnect.rtbStr.Text;
//dbConnInfo.ConnType = ConnType;
//if (!string.IsNullOrEmpty(formConnect.txtTemplatePath.Text.Trim()))
//{
// if (formConnect.txtTemplatePath.Text.Contains("@"))
// {
// TempleteProfolder = System.IO.Path.GetFullPath(@"SoftStruct");
// }
// else
// {
// TempleteProfolder = formConnect.txtTemplatePath.Text;
// }
//}
//LoadTemplate();
switch (dbConnInfo.DbClient)
{
case Model.DbType.SQLServer2000:
CDBHelper = new SQLHelper2000();
break;
case Model.DbType.SQLServer2008:
CDBHelper = new SQLHelper2008();
break;
case Model.DbType.Oracle:
CDBHelper = new OracleHelper();
break;
case Model.DbType.MySQL:
CDBHelper = new MySQLHelper();
break;
case Model.DbType.Access:
CDBHelper = new AccessHelper();
break;
case Model.DbType.Sqlite:
CDBHelper = new SqliteHelper();
break;
default:
CDBHelper = new SQLHelper2005();
break;
}
XmlHelper.Update(xmlfile, "/conf/type", "", StringUtility.ConvetTxtToXML(formConnect.CombDbType.Text));
XmlHelper.Update(xmlfile, "/conf/server", "", StringUtility.ConvetTxtToXML(formConnect.CombServerPotion.Text));
XmlHelper.Update(xmlfile, "/conf/user", "", StringUtility.ConvetTxtToXML(formConnect.txtUser.Text));
XmlHelper.Update(xmlfile, "/conf/password", "", StringUtility.ConvetTxtToXML(formConnect.txtPassWord.Text));
XmlHelper.Update(xmlfile, "/conf/database", "", StringUtility.ConvetTxtToXML(formConnect.txtDBName.Text));
//XmlHelper.Update(xmlfile, "/conf/sqlconn", "", StringUtility.ConvetTxtToXML(formConnect.rtbStr.Text));
//XmlHelper.Update(xmlfile, "/conf/templatepath", "", StringUtility.ConvetTxtToXML(formConnect.txtTemplatePath.Text));
//if (formConnect.radioButton1.Checked)
//{
// ConnType = "0";
//}
//else
//{
// ConnType = "1";
//}
//XmlHelper.Update(xmlfile, "/conf/conntype", "", ConnType);
//dbConnInfo.ConnType = ConnType;
CDBHelper.Dbinfo = dbConnInfo;
//if (ConnType == "1")
//{
// TbList = CDBHelper.getTable("");
// //GetTbs(node);
//}
//else
//{
// DBList = CDBHelper.getDB();
// //GetDBs(node);
//}
//tv.Nodes.Add(node);
//TreeNode node = new TreeNode();
//node.Text = dbConnInfo.ServerType;
//GetDBs(node, DBList);
//this.tv.Nodes.Add(node);
IList<CDataBase> Host = CDBHelper.getDB();
_CB_DB.Items.Clear();
CDBHelper.Dbinfo = dbConnInfo;
if (dbConnInfo.ConnType == "1")
{
//F_GetTables("");
}
else
{
foreach (CDataBase Temp in Host)
{
_CB_DB.Items.Add(Temp.DbName);
}
_CB_DB.SelectedIndex = 0;
//F_GetTables(_CB_DB.Items[0].ToString());
}
//if (!Directory.Exists(TempleteProfolder))
//{
// MessageBox.Show("模板位置不正确!");
// return;
//}
//else
//{
// this.cbxStructs.Items.Clear();
// DirectoryInfo Skindi = new DirectoryInfo(TempleteProfolder);
// foreach (DirectoryInfo d in Skindi.GetDirectories())
// {
// this.cbxStructs.Items.Add(d.Name);
// }
// this.cbxStructs.SelectedIndex = 0;
//}
//this.toolStripStatusLabel4.Text = "数据库已经连接!";
//islogin = true;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
Process.Start("explorer.exe", AppDomain.CurrentDomain.BaseDirectory + "RT");
}
private void Form1_Load(object sender, EventArgs e)
{
SetStyle(ControlStyles.AllPaintingInWmPaint, true); //忽略系统消息,防止图像闪烁
CheckForIllegalCrossThreadCalls = false;
}
private bool isHav(string[] list, string tag)
{
foreach (string item in list)
{
if (item == tag)
{
return true;
}
}
return false;
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(ExcelFile))
{
MessageBox.Show("至少选择Excel!");
return;
}
ExcelHelper c = new ExcelHelper();
string[] list = c.listtable(ExcelFile);
if (list == null)
{
MessageBox.Show("Excel缺Sheet!");
return;
}
if (isHav(list, "关联设置$"))
RelDt = c.ImportFromExcel(ExcelFile, "关联设置");
if (isHav(list, "字典权限控制$"))
ValuesDt = c.ImportFromExcel(ExcelFile, "字典权限控制");
if (isHav(list, "目录$"))
Dt = c.ImportFromExcel(ExcelFile, "目录");
if (Dt == null || Dt.Rows.Count <= 0)
{
MessageBox.Show("Excel无数据!");
return;
}
if (this.folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
folder = this.folderBrowserDialog1.SelectedPath;
}
if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
FormPro = new FormProcess();
FormPro.Show();
FormPro.btnClose.Click += new EventHandler(btnClose_Click);
FormPro.btnOver.Click += new EventHandler(btnOver_Click);
FormPro.btnStartOrPause.Click += new EventHandler(btnStartOrPause_Click);
_Thread = new Thread(new ThreadStart(SimpleRun));
_Thread.IsBackground = true;
_Thread.Start();
}
}
}
}