public void CreateModelsFile() { if (Frame.ConnectionStrings.Count > 0) { string dbTplFileName = Frame.MapPath("/NFinal/DB/DB.tpl"); VTemplate.Engine.TemplateDocument doc = null; for (int i = 0; i < Frame.ConnectionStrings.Count; i++) { doc = new VTemplate.Engine.TemplateDocument(dbTplFileName, System.Text.Encoding.UTF8); doc.SetValue("project", Frame.AssemblyTitle); doc.SetValue("app", config.APP.Trim('/')); doc.SetValue("database", Frame.ConnectionStrings[i].name); doc.SetValue("name", Frame.ConnectionStrings[i].name); doc.SetValue("connectionString", Frame.ConnectionStrings[i].value); doc.SetValue("providerName", Frame.ConnectionStrings[i].provider); doc.SetValue("dbType", Frame.ConnectionStrings[i].type.ToString()); doc.RenderTo(Frame.MapPath(config.Models + Frame.ConnectionStrings[i].name + ".cs")); } string fileName = Frame.MapPath("/NFinal/Template/App/Models/ConnectionStrings.cs.tpl"); doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", Frame.AssemblyTitle); doc.SetValue("app", config.APP.Trim('/')); doc.SetValue("connectionStrings", Frame.ConnectionStrings); doc.RenderTo(Frame.MapPath(config.Models + "ConnectionStrings.cs")); } }
public void InitCommon(string app) { VTemplate.Engine.TemplateDocument docCommon = null; string fileName = MapPath("/NFinal/Template/App/Common/Data/CookieInfo.tpl"); if (File.Exists(fileName)) { docCommon = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); docCommon.SetValue("project", AssemblyTitle); docCommon.SetValue("app", app); docCommon.RenderTo(getfileName(MapPath("/" + app + "/Common/Data/CookieInfo.cs"))); } fileName = MapPath("/NFinal/Template/App/Common/Data/CookieManager_Init.tpl"); if (File.Exists(fileName)) { docCommon = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); docCommon.SetValue("project", AssemblyTitle); docCommon.SetValue("app", app); docCommon.RenderTo(getfileName(MapPath("/" + app + "/Common/Data/CookieManager.cs"))); } fileName = MapPath("/NFinal/Template/App/Common/Controller.tpl"); if (File.Exists(fileName)) { docCommon = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); docCommon.SetValue("project", AssemblyTitle); docCommon.SetValue("app", app); docCommon.RenderTo(getfileName(MapPath("/" + app + "/Common/Controller.cs"))); } }
public void InitWebCompiler(string app) { string WebCompiler = ""; VTemplate.Engine.TemplateDocument docWeb = null; WebCompiler = MapPath("/NFinal/Template/App/WebCompiler.aspx.tpl"); if (File.Exists(WebCompiler)) { docWeb = new VTemplate.Engine.TemplateDocument(WebCompiler, System.Text.Encoding.UTF8); docWeb.SetValue("project", AssemblyTitle); docWeb.SetValue("app", app); docWeb.RenderTo(getfileName(MapPath("/" + app + "/WebCompiler.aspx"))); } WebCompiler = MapPath("/NFinal/Template/App/WebCompiler.aspx.cs.tpl"); if (File.Exists(WebCompiler)) { docWeb = new VTemplate.Engine.TemplateDocument(WebCompiler, System.Text.Encoding.UTF8); docWeb.SetValue("project", AssemblyTitle); docWeb.SetValue("app", app); docWeb.RenderTo(getfileName(MapPath("/" + app + "/WebCompiler.aspx.cs"))); } WebCompiler = MapPath("/NFinal/Template/App/WebCompiler.aspx.designer.cs.tpl"); if (File.Exists(WebCompiler)) { docWeb = new VTemplate.Engine.TemplateDocument(WebCompiler, System.Text.Encoding.UTF8); docWeb.SetValue("project", AssemblyTitle); docWeb.SetValue("app", app); docWeb.RenderTo(getfileName(MapPath("/" + app + "/WebCompiler.aspx.designer.cs"))); } }
// //创建入口文件 public void CreateIndex() { string page = "Default"; VTemplate.Engine.TemplateDocument doc_aspx = new VTemplate.Engine.TemplateDocument(Frame.MapPath("/NFinal/Index/Index.aspx.cs.tpl"), System.Text.Encoding.UTF8); doc_aspx.SetValue("assm", NFinal.Frame.AssemblyTitle); doc_aspx.SetValue("page", page); doc_aspx.SetValue("app", config.APP.Trim('/')); doc_aspx.RenderTo(Frame.MapPath(page + ".aspx.cs")); doc_aspx = new VTemplate.Engine.TemplateDocument(Frame.MapPath("/NFinal/Index/Index.aspx.designer.cs.tpl"), System.Text.Encoding.UTF8); doc_aspx.SetValue("assm", NFinal.Frame.AssemblyTitle); doc_aspx.SetValue("page", page); doc_aspx.SetValue("app", config.APP.Trim('/')); doc_aspx.RenderTo(Frame.MapPath(page + ".aspx.designer.cs")); doc_aspx = new VTemplate.Engine.TemplateDocument(Frame.MapPath("/NFinal/Index/Index.aspx.tpl"), System.Text.Encoding.UTF8); doc_aspx.SetValue("assm", NFinal.Frame.AssemblyTitle); doc_aspx.SetValue("page", page); doc_aspx.SetValue("app", config.APP.Trim('/')); doc_aspx.RenderTo(Frame.MapPath(page + ".aspx")); }
//创建分组路由器 public void CreateRouter() { string[] fileNames = Directory.GetFiles(Frame.MapPath(config.Controller), "*.cs", SearchOption.AllDirectories); string ClassName = null; Compiler compiler = new Compiler(); FileData fileData = null; ClassData classData = null; List <ClassData> classDataList = new List <ClassData>(); string temp = null; if (fileNames.Length > 0) { for (int i = 0; i < fileNames.Length; i++) { fileData = compiler.GetFileData(Frame.appRoot, this.config.APP, fileNames[i], System.Text.Encoding.UTF8); ClassName = Path.GetFileNameWithoutExtension(fileNames[i]); classData = fileData.GetClassData(ClassName); temp = (Frame.AssemblyTitle + config.Controller).TrimEnd('/'); //relativeName="/Manage/IndexController" //RelativeDotName=".Manage.IndexController" classData.relativeName = classData.fullName.Substring(temp.Length, classData.fullName.Length - temp.Length).Replace('.', '/'); classData.relativeDotName = classData.fullName.Substring(temp.Length, classData.fullName.Length - temp.Length); classDataList.Add(classData); } } VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(Frame.MapPath("NFinal/Template/App/Router.tpl"), System.Text.Encoding.UTF8); doc.SetValue("defaultStyle", config.defaultStyle.Trim('/')); doc.SetValue("classDataList", classDataList); doc.SetValue("namespace", config.GetFullName(fileData.projectName, config.APP)); doc.RenderTo(Frame.MapPath(config.APP + "Router.cs"), System.Text.Encoding.UTF8); }
//自动创建项目 public void CreateApp() { //创建目录 string[] folders = { config.Controller, config.Common, config.Views, config.Views + config.defaultStyle, config.Views + config.defaultStyle + "IndexController/", config.BLL, config.DAL, config.Web, config.Content, config.ContentJS, config.ContentImages, config.ContentCss, config.Models }; CreateFolders(folders); //生成首页 string fileName = Frame.MapPath(config.Controller + string.Format("Index{0}.cs", config.ControllerSuffix)); if (!File.Exists(fileName)) { VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(Frame.MapPath("/NFinal/Template/IndexController.cs.tpl"), System.Text.Encoding.UTF8); doc.SetValue("nameSpace", Frame.AssemblyTitle + "." + config.Controller.Trim('/').Replace('/', '.')); doc.RenderTo(fileName); } //生成首页 fileName = Frame.MapPath(config.Views + config.defaultStyle + "Index" + config.ControllerSuffix + "/" + "Index.aspx"); if (!File.Exists(fileName)) { File.Copy(Frame.MapPath("/NFinal/Template/Index.aspx.tpl"), fileName); } }
public Examing_State(VTemplate.Engine.TemplateDocument document) { this.Document = document; this.IsEnable = false; this.State = -2; this.Document.SetValue("state", this); }
public void InitViews(string app) { string appWebConfigPath = null; //配置Views目录的安全配置 appWebConfigPath = MapPath("/NFinal/Template/App/Views/Web.config.tpl"); if (!File.Exists(MapPath("/" + app + "/Views/Web.config"))) { File.Copy(appWebConfigPath, MapPath("/" + app + "/Views/Web.config")); } string fileName = MapPath("/NFinal/Template/App/Views/Default/Common/Public/Error.aspx.tpl"); VTemplate.Engine.TemplateDocument doc = null; if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("proejct", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Error.aspx"))); } fileName = MapPath("/NFinal/Template/App/Views/Default/Common/Public/Footer.ascx.tpl"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("proejct", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Footer.ascx"))); } fileName = MapPath("/NFinal/Template/App/Views/Default/Common/Public/Header.ascx.tpl"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("proejct", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Header.ascx"))); } fileName = MapPath("/NFinal/Template/App/Views/Default/Common/Public/Success.aspx.tpl"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("proejct", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Success.aspx"))); } fileName = MapPath("/NFinal/Template/App/Views/Default/IndexController/Index.aspx.tpl"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("proejct", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Views/Default/IndexController/Index.aspx"))); } }
/// <summary> /// 创建主路由 /// </summary> /// <param name="apps"></param> public void CreateMain(string[] apps) { VTemplate.Engine.TemplateDocument doc = null; doc = new VTemplate.Engine.TemplateDocument(MapPath("NFinal/Template/Main.tpl"), System.Text.Encoding.UTF8); doc.SetValue("project", NFinal.Frame.AssemblyTitle); doc.SetValue("apps", apps); doc.SetValue("ControllerSuffix", "Controller"); doc.RenderTo(MapPath("NFinal/Main.cs"), System.Text.Encoding.UTF8); }
public void InitWeb(string app) { VTemplate.Engine.TemplateDocument doc = null; string fileName = null; fileName = MapPath("/NFinal/Template/App/Web/Default/Common/Public/Error.cs.tpl"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Error.cs"))); } fileName = MapPath("/NFinal/Template/App/Web/Default/Common/Public/Error.html"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Error.html"))); } fileName = MapPath("/NFinal/Template/App/Web/Default/Common/Public/Success.cs.tpl"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Success.cs"))); } fileName = MapPath("/NFinal/Template/App/Web/Default/Common/Public/Success.html"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Success.html"))); } fileName = MapPath("/NFinal/Template/App/Web/Default/IndexController/Index.cs.tpl"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Web/Default/IndexController/Index.cs"))); } fileName = MapPath("/NFinal/Template/App/Web/Default/IndexController/Index.html"); if (File.Exists(fileName)) { doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Web/Default/IndexController/Index.html"))); } }
public void InitConfig(string app) { string fileName = MapPath("/NFinal/Template/App/Config.tpl"); if (File.Exists(fileName)) { VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("namespace", AssemblyTitle + "." + app); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Config.cs"))); } }
public void InitMain(string[] apps) { string fileName = MapPath("/NFinal/Template/Main.tpl"); if (File.Exists(fileName)) { VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("apps", apps); doc.SetValue("project", AssemblyTitle); doc.RenderTo(MapPath("/NFinal/Main.cs")); } }
public int SetMagicConnection(string methodName, ref string csharpCode, string appRoot) { string conParttern = @"Models\s*.\s*([_a-zA-Z0-9]+)\s*.\s*(Open|Close)Connection\s*\(\s*\)\s*;"; Regex reg = new Regex(conParttern); MatchCollection mac = reg.Matches(csharpCode); string dataName = null; NFinal.DB.ConnectionString connectionString = null; string fileName = null; VTemplate.Engine.TemplateDocument doc = null; string conCode = null; int relative_position = 0; for (int i = 0; i < mac.Count; i++) { dataName = mac[i].Groups[1].Value; //查找出sql语句中用的是哪个数据库 connectionString = GetConnectionString(dataName); if (mac[i].Groups[2].Value == "Open") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\Open.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("dbName", dataName); conCode = doc.GetRenderText(); relative_position += Replace(ref csharpCode, mac[i].Index + relative_position, mac[i].Length, conCode); } else { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\Close.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("dbName", dataName); conCode = doc.GetRenderText(); relative_position += Replace(ref csharpCode, mac[i].Index + relative_position, mac[i].Length, conCode); } } return(relative_position); }
public void CreateCommonFile() { if (!Directory.Exists(Frame.MapPath(config.Common))) { Directory.CreateDirectory(Frame.MapPath(config.Common)); } if (!Directory.Exists(Frame.MapPath(config.Common + "Data"))) { Directory.CreateDirectory(Frame.MapPath(config.Common + "Data")); } VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument( Frame.MapPath("/NFinal/Template/App/Common/Data/CookieInfo.tpl"), System.Text.Encoding.UTF8); doc.SetValue("project", Frame.AssemblyTitle); doc.SetValue("app", config.APP.Trim('/')); doc.RenderTo(Frame.MapPath(config.Common + "Data/CookieInfo.cs")); CreateCookieManager(); }
public void InitModels(string app) { string fileName = MapPath("/NFinal/Template/App/Models/Common.cs.tpl"); if (File.Exists(fileName)) { VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Models/Common.cs"))); } fileName = MapPath("/NFinal/Template/App/Models/ConnectionStrings_Init.cs.tpl"); if (File.Exists(fileName)) { VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Models/ConnectionStrings.cs"))); } }
public void InitControllers(string app) { string fileName = MapPath("/NFinal/Template/App/Controllers/Common/Public.cs.tpl"); if (File.Exists(fileName)) { VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Controllers/Common/Public.cs"))); } fileName = MapPath("/NFinal/Template/App/Controllers/IndexController.cs.tpl"); if (File.Exists(fileName)) { VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("project", AssemblyTitle); doc.SetValue("app", app); doc.RenderTo(getfileName(MapPath("/" + app + "/Controllers/IndexController.cs"))); } }
/// <summary> /// 数据库函数替换类 /// </summary> /// <param name="methodName">函数名</param> /// <param name="dbFunctionData">函数信息</param> /// <param name="appRoot">网站根目录</param> /// <returns></returns> public string SetMagicStruct(string methodName, DbFunctionData dbFunctionData, List <NFinal.Compile.StructField> structFieldList, string appRoot) { string result = null; if (dbFunctionData.functionName == "QueryAll" || dbFunctionData.functionName == "QueryRow" || dbFunctionData.functionName == "Page" || dbFunctionData.functionName == "QueryRandom" || dbFunctionData.functionName == "QueryTop") { NFinal.DB.ConnectionString connectionString = null; connectionString = GetConnectionString(dbFunctionData.connectionName); string type = connectionString.type.ToString(); string fileName = appRoot + "NFinal\\SqlTemplate\\" + type + "\\Struct.txt"; VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionData.varName); doc.SetValue("dbType", type); doc.SetValue("fields", dbFunctionData.fields); doc.SetValue("structFields", structFieldList); result = doc.GetRenderText(); } return(result); }
public void Compile(string baseName, MethodData methodData, string StructDatas, List <ViewData> viewDatas, string nameSpace, string ClassName, Config config) { ViewData viewData = null; //模板目录, string tplDir = ""; //模板文件 string tplFileName = ""; for (int i = 0; i < viewDatas.Count; i++) { viewData = viewDatas[i]; bool IsVarName = false; //获取模板样式变量或字符串 if (string.IsNullOrEmpty(viewData.templateStyle)) { //此处当字符串来算. IsVarName = false; viewData.templateStyle = "\"" + config.defaultStyle.Trim('/') + "\""; } else { if (viewData.templateStyle.IndexOf('\"') > -1) { IsVarName = false; } else { IsVarName = true; } } //如果是字符串则直接取值就行了. string[] templateStyle = null; string[] styles = Directory.GetDirectories(Frame.MapPath(config.Views)); int defaultTemplateStyleIndex = 0; string[] sharpCodes = null; if (styles.Length > 0) { sharpCodes = new string[styles.Length]; templateStyle = new string[styles.Length]; for (int j = 0; j < styles.Length; j++) { templateStyle[j] = new DirectoryInfo(styles[j]).Name; //如果不是变量而是字符串 if (!IsVarName) { if (viewData.templateStyle.Trim('\"') == templateStyle[j]) { defaultTemplateStyleIndex = j; } else { continue; } } //如果参数是字符串 else { if (templateStyle[j] == config.defaultStyle.Trim('/')) { defaultTemplateStyleIndex = j; } } tplDir = config.ChangeControllerName(config.Views + templateStyle[j] + '/', (nameSpace + '.' + ClassName).Replace('.', '/')) + "/"; if (!string.IsNullOrEmpty(viewData.template)) { //如果参数为/IndexController/Index.aspx if (viewData.template.IndexOf('/') == 0) { tplFileName = Frame.MapPath(config.Views + templateStyle[j] + viewData.template); } //如果参数为IndexController/Index.aspx else if (viewData.template.IndexOf('/') > 0) { tplFileName = Frame.MapPath(tplDir.Substring(0, tplDir.Length - ClassName.Length - 1) + viewData.template); } //如果参数为Index.aspx else { tplFileName = Frame.MapPath(tplDir + viewData.template); } } //如果参数为空 else { tplFileName = Frame.MapPath(tplDir + methodData.name + ".aspx"); } tplDir = Path.GetDirectoryName(tplFileName); if (!Directory.Exists(tplDir)) { Directory.CreateDirectory(tplDir); } //如果模板存在,则重写自动提示类 if (File.Exists(tplFileName)) { string tplFileClassName = tplFileName + ".cs"; //重写自动提示类 StreamReader tplFileReader = new StreamReader(tplFileName, System.Text.Encoding.UTF8); string tplFileCodeString = tplFileReader.ReadToEnd(); tplFileReader.Close(); string aspxPageHeaderPattern = @"<%@\s+(Page|Control)[^%]+%>"; string aspxPageAttrInheritsPattern = @"Inherits\s*=\s*""([^""]+)"""; string aspxPageAttrCodePattern = @"Code(?:Behind|File)\s*=\s*""([^""]+)"""; Regex aspxPageHeaderReg = new Regex(aspxPageHeaderPattern); Match aspxPageHeaderMat = aspxPageHeaderReg.Match(tplFileCodeString); if (aspxPageHeaderMat.Success) { string aspxPageHeaderString = aspxPageHeaderMat.Value; Regex aspxPageAttrInheritsReg = new Regex(aspxPageAttrInheritsPattern); Match aspxPageAttrInheritsMat = aspxPageAttrInheritsReg.Match(aspxPageHeaderString); Regex aspxPageAttrCodeReg = new Regex(aspxPageAttrCodePattern); Match aspxPageAttrCodeMat = aspxPageAttrCodeReg.Match(aspxPageHeaderString); if (aspxPageAttrCodeMat.Success && aspxPageAttrInheritsMat.Success) { string aspxPageAttrCodeFileName = Path.Combine(tplDir, aspxPageAttrCodeMat.Groups[1].Value); string aspxPageInheritsString = aspxPageAttrInheritsMat.Groups[1].Value; string aspxPageNameSpace = aspxPageInheritsString.Substring(0, aspxPageInheritsString.LastIndexOf('.')); string aspxPageClassName = aspxPageInheritsString.Substring(aspxPageInheritsString.LastIndexOf('.') + 1); //如果模板样式是变量 VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument(Frame.MapPath("/NFinal/Template/AutoComplete.tpl"), System.Text.Encoding.UTF8); doc.SetValue("aspxPageNameSpace", aspxPageNameSpace); doc.SetValue("aspxPageClassName", aspxPageClassName); doc.SetValue("baseName", baseName); doc.SetValue("StructDatas", StructDatas); doc.SetValue("parameterDataList", methodData.parameterDataList); //去掉重复的声明 List <DbFunctionData> functionDataList = new List <DbFunctionData>(); for (int m = 0; m < methodData.dbFunctions.Count; m++) { bool hasDbFunctionValue = false; for (int n = 0; n < functionDataList.Count; n++) { if (functionDataList[n].varName == methodData.dbFunctions[m].varName) { hasDbFunctionValue = true; } } if (hasDbFunctionValue == false && methodData.dbFunctions[m].type == "var") { functionDataList.Add(methodData.dbFunctions[m]); } } CSharpDeclarationParser csharpDeclarationParser = new CSharpDeclarationParser(); List <CSharpDeclaration> csharpDeclarationList = csharpDeclarationParser.Parse(methodData.Content); doc.SetValue("methodName", methodData.name); doc.SetValue("functionDataList", functionDataList); doc.SetValue("csharpDeclarationList", csharpDeclarationList); doc.RenderTo(tplFileClassName, System.Text.Encoding.UTF8); } } } else { sharpCodes[j] = ""; } } StringWriter swTemplate = new StringWriter(); //如果参数是变量,而非字符串 if (IsVarName) { swTemplate.Write("switch("); swTemplate.Write(viewData.templateStyle); swTemplate.Write(")\r\n\t\t\t{\r\n"); if (styles.Length > 0) { for (int j = 0; j < styles.Length; j++) { if (j != defaultTemplateStyleIndex) { swTemplate.Write("\t\t\t\tcase \""); swTemplate.Write(templateStyle[j]); swTemplate.Write("\":\r\n\t\t\t\t{\r\n"); swTemplate.Write(sharpCodes[j]); swTemplate.Write("\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n"); } } } if (styles.Length > 0) { for (int j = 0; j < styles.Length; j++) { if (j == defaultTemplateStyleIndex) { swTemplate.Write("\t\t\t\tdefault :\r\n\t\t\t\t{\r\n"); swTemplate.Write(sharpCodes[j]); swTemplate.Write("\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n"); } } } swTemplate.Write("\t\t\t}\r\n"); } else { if (styles.Length > 0) { for (int j = 0; j < styles.Length; j++) { if (j == defaultTemplateStyleIndex) { swTemplate.Write("\r\n"); swTemplate.Write(sharpCodes[j]); } } } } } } }
//创建Cookie操作类 public void CreateCookieManager() { StreamReader sr = new StreamReader(Frame.MapPath(config.Common + "Data/CookieInfo.cs"), System.Text.Encoding.UTF8); string CookieInfoCodeString = sr.ReadToEnd(); Compile.CSharpDeclarationParser parser = new CSharpDeclarationParser(); List <Compile.CSharpDeclaration> declarations = parser.Parse(CookieInfoCodeString); for (int i = 0; i < declarations.Count; i++) { switch (declarations[i].typeName.Split('.')[0]) { case "Int32": goto case "int"; case "int": declarations[i].covertMethod = "Convert.ToInt32({0})"; break; case "Int64": goto case "long"; case "long": declarations[i].covertMethod = "Convert.ToInt64({0})"; break; case "Int16": goto case "short"; case "short": declarations[i].covertMethod = "Convert.ToInt16({0})"; break; case "Byte": goto case "byte"; case "byte": declarations[i].covertMethod = "Convert.ToByte({0})"; break; case "Boolean": goto case "bool"; case "bool": declarations[i].covertMethod = "Convert.ToBoolean({0})"; break; case "SByte": goto case "byte"; case "sbyte": declarations[i].covertMethod = "Convert.ToSByte({0})"; break; case "UInt16": goto case "ushort"; case "ushort": declarations[i].covertMethod = "Convert.ToUInt16({0})"; break; case "UInt32": goto case "uint"; case "uint": declarations[i].covertMethod = "Convert.ToUInt32({0})"; break; case "UInt64": goto case "ulong"; case "ulong": declarations[i].covertMethod = "Convert.ToUInt64({0})"; break; case "Single": goto case "float"; case "float": declarations[i].covertMethod = "Convert.ToSingle({0})"; break; case "Double": goto case "double"; case "double": declarations[i].covertMethod = "Convert.ToDouble({0})"; break; case "Decimal": goto case "decimal"; case "decimal": declarations[i].covertMethod = "Convert.ToDecimal({0})"; break; case "DateTime": declarations[i].covertMethod = "Convert.ToDateTime({0})"; break; case "String": goto case "string"; case "string": declarations[i].covertMethod = "{0}"; break; default: declarations[i].covertMethod = "{0}.ToString()"; break; } string varCookie = string.Format("_context.Request.Cookies[\"{0}\"].Value", declarations[i].varName); declarations[i].covertMethod = string.Format(declarations[i].covertMethod, varCookie); } VTemplate.Engine.TemplateDocument doc = new VTemplate.Engine.TemplateDocument( Frame.MapPath("/NFinal/Template/App/Common/Data/CookieManager.tpl"), System.Text.Encoding.UTF8); doc.SetValue("project", Frame.AssemblyTitle); doc.SetValue("app", config.APP.Trim('/')); doc.SetValue("declarations", declarations); doc.RenderTo(Frame.MapPath(config.Common + "Data/CookieManager.cs")); }
/// <summary> /// 执行数据库魔法函数 /// </summary> /// <param name="methodName">Controller的函数名</param> /// <param name="csharpFileCode">Controller的函数内的代码</param> /// <param name="dbFunctionDatas">代码内分析出的魔法函数</param> /// <param name="appRoot">项目的根目录</param> /// <returns></returns> public int SetMagicFunction(string methodName, ref string csharpFileCode, int relative_position, List <DbFunctionData> dbFunctionDatas, string appRoot) { if (dbFunctionDatas.Count > 0) { string webCsharpCode = ""; VTemplate.Engine.TemplateDocument doc = null; NFinal.DB.ConnectionString connectionString = null; string fileName = null; for (int i = 0; i < dbFunctionDatas.Count; i++) { connectionString = GetConnectionString(dbFunctionDatas[i].connectionName); if (connectionString != null) { if (dbFunctionDatas[i].functionName == "QueryAll") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\QueryAll.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); doc.SetValue("sql", dbFunctionDatas[i].sql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "QueryRow") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\QueryRow.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8 ); doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); doc.SetValue("sql", dbFunctionDatas[i].sql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "Insert") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\Insert.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8 ); doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); doc.SetValue("sql", dbFunctionDatas[i].sql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "Update") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\Update.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8 ); doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); doc.SetValue("sql", dbFunctionDatas[i].sql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "Delete") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\Update.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8 ); doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); doc.SetValue("sql", dbFunctionDatas[i].sql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "QueryObject") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\QueryObject.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8 ); doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); doc.SetValue("sql", dbFunctionDatas[i].sql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); doc.SetValue("convertMethodName", dbFunctionDatas[i].convertMethodName); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "Page") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\Page.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8 ); doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); doc.SetValue("fields", dbFunctionDatas[i].fields); //分页参数解析 PageSqlAnalyse pageStatement = new PageSqlAnalyse(dbFunctionDatas[i].sql, connectionString.type); pageStatement.Parse(); doc.SetValue("pageSql", pageStatement.pageSql); doc.SetValue("countSql", pageStatement.countSql); doc.SetValue("pageSizeVarName", dbFunctionDatas[i].parameters[1]); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); doc.SetValue("convertMethodName", dbFunctionDatas[i].convertMethodName); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "QueryRandom") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\QueryRandom.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); //select 语句 转为选取某随机行的语句 RandomSqlAnalyse random = new RandomSqlAnalyse(dbFunctionDatas[i].sql, connectionString.type); random.Parse(); doc.SetValue("topNumber", dbFunctionDatas[i].parameters[1]); doc.SetValue("sql", random.randomSql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } if (dbFunctionDatas[i].functionName == "QueryTop") { fileName = appRoot + "NFinal\\SqlTemplate\\" + connectionString.type.ToString() + "\\QueryTop.txt"; doc = new VTemplate.Engine.TemplateDocument( fileName, System.Text.Encoding.UTF8); doc.SetValue("functionName", methodName); doc.SetValue("varName", dbFunctionDatas[i].varName); doc.SetValue("dbName", dbFunctionDatas[i].connectionName); //select 语句 转为选取某随机行的语句 TopSqlAnalyse top = new TopSqlAnalyse(dbFunctionDatas[i].sql, connectionString.type); top.Parse(); doc.SetValue("topNumber", dbFunctionDatas[i].parameters[1]); doc.SetValue("sql", top.topSql); doc.SetValue("fields", dbFunctionDatas[i].fields); doc.SetValue("sqlVarParameters", dbFunctionDatas[i].sqlVarParameters); webCsharpCode = doc.GetRenderText(); relative_position += Replace(ref csharpFileCode, relative_position + dbFunctionDatas[i].index, dbFunctionDatas[i].length, webCsharpCode); } } } } return(relative_position); }
//建立编译文件 public void CreateCompile(bool build) { string[] fileNames; //获取要生成的文件 if (genConfig != null) { if (genConfig.controllerFiles.Count > 0) { fileNames = new string[genConfig.controllerFiles.Count]; for (int i = 0; i < fileNames.Length; i++) { fileNames[i] = Frame.MapPath(genConfig.controllerFiles[i]); } } else { return; } } else { if (!Directory.Exists(Frame.MapPath(config.Controller))) { return; } //获取所有的controls文件 fileNames = Directory.GetFiles(Frame.MapPath(config.Controller), "*.cs", SearchOption.AllDirectories); if (fileNames == null || fileNames.Length < 1) { return; } } //生成的代码 string compileCode = ""; //类名称 string ClassName = ""; //前面的字符串部分添加或删除后,后面的代码的相对位置 int relative_postion = 0; if (fileNames.Length > 0) { Compiler com = new Compiler(); FileData fileData = null; ClassData classData = null; MethodData methodData = null; StreamWriter sw = null; VTemplate.Engine.TemplateDocument swDebug = null; //VTemplate.Engine.TemplateDocument swAspx = null; string compileFileName = ""; string compileDir = ""; string debugFileName = ""; string methodContent = ""; for (int i = 0; i < fileNames.Length; i++) { fileData = fileData = com.GetFileData(Frame.appRoot, this.config.APP, fileNames[i], System.Text.Encoding.UTF8); ClassName = Path.GetFileNameWithoutExtension(fileNames[i]); classData = fileData.GetClassData(ClassName); if (classData.MethodDataList.Count > 0) { for (int j = 0; j < classData.MethodDataList.Count; j++) { //只有公开方法才能访问 if (classData.MethodDataList[j].isPublic) { relative_postion = 0; compileCode = fileData.csharpCode.ToString(); methodData = classData.MethodDataList[j]; //相对 compileDir = config.ChangeControllerName(config.Web + config.defaultStyle, (fileData.nameSpace + '.' + ClassName).Replace('.', '/')) + "/"; //绝对 compileFileName = Frame.MapPath(compileDir + methodData.name + ".cs"); if (!Directory.Exists(Path.GetDirectoryName(compileFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(compileFileName)); } //调试文件 debugFileName = Frame.MapPath(compileDir + methodData.name + ".html"); //输出调试文件 if (!File.Exists(debugFileName)) { swDebug = new VTemplate.Engine.TemplateDocument(Frame.MapPath("/NFinal/Template/Debug.tpl"), System.Text.Encoding.UTF8); swDebug.SetValue("Url", config.ChangeControllerName(config.APP, (fileData.nameSpace + '.' + ClassName).Replace('.', '/')) + "/" + methodData.name + ".htm"); swDebug.RenderTo(debugFileName, System.Text.Encoding.UTF8); } relative_postion += Replace(ref compileCode, relative_postion + fileData.start, fileData.length, "namespace " + (Frame.AssemblyTitle + compileDir.TrimEnd('/')).Replace('/', '.') + "\r\n{"); relative_postion += Replace(ref compileCode, relative_postion + classData.start, classData.length, "public class " + methodData.name + "Action " + (string.IsNullOrEmpty(classData.baseName) ? "" : " : " + classData.baseName) + "\r\n\t{" //添加初始化函数 + "\r\n\t\tpublic " + methodData.name + "Action(System.IO.TextWriter tw):base(tw){}" + "\r\n\t\tpublic " + methodData.name + "Action(string fileName) : base(fileName) {}"); //循环内部所有方法 for (int k = 0; k < classData.MethodDataList.Count; k++) { methodData = classData.MethodDataList[k]; //如果两个相等,则进行替换 if (j == k || (!classData.MethodDataList[k].isPublic)) { #region "替换原有方法" //排除非公开和非基类的方法,替换原有方法体 //if (methodData.isPublic) { methodContent = methodData.Content; SqlCompiler sqlCompiler = new NFinal.Compile.SqlCompiler(); //从代码中分析出数据库相关函数 List <DbFunctionData> dbFunctions = sqlCompiler.Compile(com.DeleteComment(methodContent)); if (dbFunctions.Count > 0) { SqlAnalyse analyse = new SqlAnalyse(); //与数据库相结合,从sql语句中分析出所有的表信息,列信息 methodData.dbFunctions = analyse.FillFunctionDataList(NFinal.DB.Coding.DB.DbStore, dbFunctions); } //数据库函数替换 int content_relative_position = 0; string StructDatas = string.Empty; if (dbFunctions.Count > 0) { bool hasSameVarName = false; List <string> varNames = new List <string>(); //添加struct类型 for (int s = 0; s < dbFunctions.Count; s++) { //去除重复项 if (varNames.Count > 0) { hasSameVarName = false; for (int c = 0; c < varNames.Count; c++) { //如果发现重复项,则跳过循环 if (varNames[c] == dbFunctions[s].varName) { hasSameVarName = true; break; } } if (hasSameVarName) { continue; } } varNames.Add(dbFunctions[s].varName); //分析出sql返回的List<dynamic>和dynamic类型是否有用AddNewField(string fileName,Type t);添加相关的类型 NewField newFiled = new NewField(dbFunctions[s].varName); List <NFinal.Compile.StructField> structFieldList = newFiled.GetFields(ref methodContent, methodData.name); //添加struct字段 string StructData = sqlCompiler.SetMagicStruct(methodData.name, dbFunctions[s], structFieldList, Frame.appRoot); StructDatas += StructData; if (!string.IsNullOrEmpty(StructData)) { compileCode = compileCode.Insert(methodData.start + relative_postion, StructData); relative_postion += StructData.Length; } } //更换函数中的数据库操作 content_relative_position += sqlCompiler.SetMagicFunction(methodData.name, ref methodContent, content_relative_position, methodData.dbFunctions, Frame.appRoot); //分析并更换其中的连接字符串 content_relative_position += sqlCompiler.SetMagicConnection(methodData.name, ref methodContent, Frame.appRoot ); } if (methodData.parameterTypeAndNames != string.Empty) { relative_postion += Replace(ref compileCode, relative_postion + methodData.parametersIndex, methodData.parametersLength, methodData.parameterTypeAndNames); } //从代码中分析出views函数 NFinal.Compile.ViewCompiler viewCompiler = new NFinal.Compile.ViewCompiler(); List <ViewData> views = viewCompiler.Compile(methodContent); //模版替换 if (views.Count > 0) { content_relative_position = 0; content_relative_position = viewCompiler.SetMagicFunction(ref methodContent, content_relative_position, fileData.nameSpace, ClassName, methodData.name, views, config); } if (build) { relative_postion += Replace(ref compileCode, relative_postion + methodData.position, methodData.Content.Length, methodContent); } else { relative_postion += Replace(ref compileCode, relative_postion + methodData.position, methodData.Content.Length, string.Empty); } //生成自动提示类 //views,Structs,DBFunctions AutoCompleteCompiler autoComplete = new AutoCompleteCompiler(); autoComplete.Compile(classData.baseName, methodData, StructDatas, views, fileData.nameSpace, ClassName, config); } #endregion } //如果两个不相等 else { compileCode = compileCode.Remove(relative_postion + classData.MethodDataList[k].start, classData.MethodDataList[k].length + classData.MethodDataList[k].Content.Length + 1);//去掉最后一个} relative_postion -= classData.MethodDataList[k].length + classData.MethodDataList[k].Content.Length + 1; } } //写aspx页面的自动提示层 //写Web层.class文件 sw = new StreamWriter(compileFileName, false, System.Text.Encoding.UTF8); sw.Write(compileCode); sw.Close(); } } } } } }
//自动配置WebConfig public static string[] SetWebConfig(IISVersion version, string appRoot, string AppName) { Config.appRoot = appRoot; Config.AssemblyTitle = new DirectoryInfo(Config.appRoot).Name; //文档是否变动 bool changed = false; //配置.net信息 string webConfig = MapPath("/Web.config"); if (!File.Exists(webConfig)) { changed = true; File.Copy(MapPath("/NFinal/Template/Web.config.tpl"), MapPath("/Web.config")); File.Copy(MapPath("/NFinal/Template/Web.config.Debug.tpl"), MapPath("/Web.Debug.config")); File.Copy(MapPath("/NFinal/Template/Web.config.Release.tpl"), MapPath("/Web.Release.config")); } //根据环境配置webconfig System.Xml.XmlDocument doc = new XmlDocument(); doc.Load(webConfig); XmlNode root = doc.DocumentElement; if (root == null) { return(null); } //首选注释掉ConnectionString连接,以免连接字符串不正确而导致生成失败 XmlNode connsNode = doc.DocumentElement.SelectSingleNode("connectionStrings/add[@name='Common']"); XmlNode connsNodeRoot = doc.DocumentElement.SelectSingleNode("connectionStrings"); //如果通用数据库没有添加,则注释掉原有的连接,建立通用连接 if (connsNode == null) { changed = true; if (connsNodeRoot == null) { connsNodeRoot = doc.CreateElement("connectionStrings"); doc.DocumentElement.AppendChild(connsNodeRoot); } connsNodeRoot.InnerXml = "<!--" + connsNodeRoot.InnerXml + "-->" + "<add name=\"Common\" connectionString=\"Data Source=|DataDirectory|\\Common.db;Pooling=true;FailIfMissing=false\" providerName=\"System.Data.SQLite\"/>"; } //读取Apps中的值 if (string.IsNullOrEmpty(AppName)) { AppName = "App"; } XmlNode appsNode = doc.DocumentElement.SelectSingleNode("appSettings/add[@key='Apps']"); string[] Apps = null; List <string> AppsList = new List <string>(); if (appsNode != null && appsNode.Attributes.Count > 0 && appsNode.Attributes["value"] != null) { if (appsNode.Attributes["value"].Value.Trim() != string.Empty) { Apps = appsNode.Attributes["value"].Value.Split(','); for (int i = 0; i < Apps.Length; i++) { if (Directory.Exists(MapPath("/" + Apps[i]))) { AppsList.Add(Apps[i]); } } bool hasAppName = false; for (int i = 0; i < Apps.Length; i++) { if (AppName == Apps[i]) { hasAppName = true; } } if (!hasAppName) { changed = true; AppsList.Add(AppName); Apps = AppsList.ToArray(); appsNode.Attributes["value"].Value = String.Join(",", Apps); } } else { changed = true; Apps = new string[] { AppName }; appsNode.Attributes["value"].Value = AppName; AppsList.Add(AppName); Apps = AppsList.ToArray(); appsNode.Attributes["value"].Value = String.Join(",", Apps); } } else { changed = true; XmlNode appSettingNode = CreateXMLPath(doc, "configuration/appSettings"); appsNode = doc.CreateElement("add"); XmlAttribute attrKey = doc.CreateAttribute("key"); attrKey.Value = "Apps"; XmlAttribute attrValue = doc.CreateAttribute("value"); attrValue.Value = AppName; appsNode.Attributes.RemoveAll(); appsNode.Attributes.Append(attrKey); appsNode.Attributes.Append(attrValue); appSettingNode.AppendChild(appsNode); Apps = new string[] { AppName }; AppsList.Add(AppName); Apps = AppsList.ToArray(); appsNode.Attributes["value"].Value = String.Join(",", Apps); } //读取是否自动生成 XmlNode autoGenerationNode = doc.DocumentElement.SelectSingleNode("appSettings/add[@key='AutoGeneration']"); bool autoGeneration = false; if (autoGenerationNode != null) { autoGeneration = autoGenerationNode.Attributes["value"].Value.ToLower() == "true"; } else { changed = true; XmlNode appSettingNode = CreateXMLPath(doc, "configuration/appSettings"); appsNode = doc.CreateElement("add"); XmlAttribute attrKey = doc.CreateAttribute("key"); attrKey.Value = "AutoGeneration"; XmlAttribute attrValue = doc.CreateAttribute("value"); attrValue.Value = "false"; appsNode.Attributes.RemoveAll(); appsNode.Attributes.Append(attrKey); appsNode.Attributes.Append(attrValue); appSettingNode.AppendChild(appsNode); autoGeneration = false; } Config.autoGeneration = autoGeneration; SetAutoCreateConfig(autoGeneration); //创建URL重写的主页文件 if (!File.Exists(MapPath("/Index.html"))) { VTemplate.Engine.TemplateDocument docIndex = new VTemplate.Engine.TemplateDocument(MapPath("/NFinal/Template/Index.html"), System.Text.Encoding.UTF8); docIndex.SetValue("App", Apps[0]); docIndex.RenderTo(MapPath("/Index.html")); } //删除UrlRewriter string urlRewriterFileName = MapPath("/bin/URLRewriter.dll"); if (File.Exists(urlRewriterFileName)) { File.Delete(urlRewriterFileName); } //添加UrlRewriter XmlNode nodeConfigSection = doc.DocumentElement.SelectSingleNode("configSections/section[@name='RewriterConfig']"); if (nodeConfigSection == null) { changed = true; XmlNode nodeSection = doc.CreateElement("section"); XmlAttribute attrName = doc.CreateAttribute("name"); attrName.Value = "RewriterConfig"; XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "NFinal.URLRewriter.Config.RewriterConfigSerializerSectionHandler"; nodeSection.Attributes.Append(attrName); nodeSection.Attributes.Append(attrType); XmlNode nodeConfigSections = doc.DocumentElement.SelectSingleNode("configSections"); if (nodeConfigSections == null) { nodeConfigSections = doc.CreateElement("configSections"); doc.DocumentElement.InsertBefore(nodeConfigSections, doc.DocumentElement.FirstChild); } nodeConfigSections.AppendChild(nodeSection); } XmlNode nodeRewriteSection = doc.DocumentElement.SelectSingleNode("configSections/section[@name='RewriterConfig']"); //修正属性 if (nodeRewriteSection.Attributes["type"].Value.IndexOf(",") > -1) { changed = true; nodeRewriteSection.Attributes["type"].Value = "NFinal.URLRewriter.Config.RewriterConfigSerializerSectionHandler"; } XmlNode nodeRewriterConfig = doc.DocumentElement.SelectSingleNode("RewriterConfig"); if (nodeRewriterConfig == null) { changed = true; XmlNode nodeRules = CreateXMLPath(doc, "configuration/RewriterConfig/Rules"); XmlNode nodeRewriterRule = doc.CreateElement("RewriterRule"); XmlNode nodeLookFor = doc.CreateElement("LookFor"); nodeLookFor.InnerText = "~/Index.html"; XmlNode nodeSendTo = doc.CreateElement("SendTo"); nodeSendTo.InnerText = string.Format("~/{0}/IndexController/Index.htm", AppName); nodeRewriterRule.AppendChild(nodeLookFor); nodeRewriterRule.AppendChild(nodeSendTo); nodeRules.AppendChild(nodeRewriterRule); } else { XmlNodeList nodeRewriterRules = doc.DocumentElement.SelectNodes("RewriterConfig/Rules/RewriterRule"); if (nodeRewriterRules != null) { for (int i = 0; i < nodeRewriterRules.Count; i++) { XmlNode nodeLookFor = nodeRewriterRules[i].SelectSingleNode("LookFor"); if (nodeLookFor != null && nodeLookFor.InnerText == "~/Index.html") { XmlNode nodeSendTo = nodeRewriterRules[i].SelectSingleNode("SendTo"); if (nodeSendTo != null) { changed = true; nodeSendTo.InnerText = string.Format("~/{0}/IndexController/Index.htm", AppName); } } } } } //如果是IIS7,IIS8新版本,要添加system.webserver配置节 if (version == IISVersion.IIS7 || version == IISVersion.IIS8) { //取消验证 XmlNode newValidationNode = doc.DocumentElement.SelectSingleNode("system.webServer/validation"); if (newValidationNode == null) { newValidationNode = CreateXMLPath(doc, "configuration/system.webServer/validation"); } newValidationNode = doc.DocumentElement.SelectSingleNode("system.webServer/validation"); if (newValidationNode.Attributes["validateIntegratedModeConfiguration"] != null) { newValidationNode.Attributes["validateIntegratedModeConfiguration"].Value = "false"; } else { XmlAttribute validateIntegratedModeConfigurationAttr = doc.CreateAttribute("validateIntegratedModeConfiguration"); validateIntegratedModeConfigurationAttr.Value = "false"; newValidationNode.Attributes.Append(validateIntegratedModeConfigurationAttr); } //添加NFinal节点属性 XmlNode newFactoryNode = doc.DocumentElement.SelectSingleNode("system.webServer/handlers/add[@type='NFinal.Handler.HandlerFactory']"); //不存在则添加 if (newFactoryNode == null) { changed = true; XmlNode handlersNode = CreateXMLPath(doc, "configuration/system.webServer/handlers"); XmlNode NFinalHandlerNode = doc.CreateElement("add"); XmlAttribute attrName = doc.CreateAttribute("name"); attrName.Value = "NFinalHandlerFactory"; XmlAttribute attrVerb = doc.CreateAttribute("verb"); attrVerb.Value = "*"; XmlAttribute attrPath = doc.CreateAttribute("path"); attrPath.Value = "*.htm"; XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "NFinal.Handler.HandlerFactory"; XmlAttribute attrPreCondition = doc.CreateAttribute("preCondition"); attrPreCondition.Value = "integratedMode"; NFinalHandlerNode.Attributes.RemoveAll(); NFinalHandlerNode.Attributes.Append(attrName); NFinalHandlerNode.Attributes.Append(attrVerb); NFinalHandlerNode.Attributes.Append(attrPath); NFinalHandlerNode.Attributes.Append(attrType); NFinalHandlerNode.Attributes.Append(attrPreCondition); handlersNode.AppendChild(NFinalHandlerNode); } //添加Rewriter节点属性 XmlNode newRewriterNode = doc.DocumentElement.SelectSingleNode("system.webServer/modules/add[@name='ModuleRewriter']"); if (newRewriterNode == null) { changed = true; XmlNode modulesNode = CreateXMLPath(doc, "configuration/system.webServer/modules"); XmlNode urlRewriterNode = doc.CreateElement("add"); XmlAttribute attrName = doc.CreateAttribute("name"); attrName.Value = "ModuleRewriter"; XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "NFinal.URLRewriter.ModuleRewriter"; urlRewriterNode.Attributes.Append(attrName); urlRewriterNode.Attributes.Append(attrType); modulesNode.AppendChild(urlRewriterNode); } XmlNode nodeModules = doc.DocumentElement.SelectSingleNode("system.webServer/modules/add[@name='ModuleRewriter']"); if (nodeModules.Attributes["type"] != null) { if (nodeModules.Attributes["type"].Value.IndexOf(",") > -1) { changed = true; nodeModules.Attributes["type"].Value = "NFinal.URLRewriter.ModuleRewriter"; } } } //IIS8下要删除老的配置节点 if (version == IISVersion.IIS8) { XmlNode FactoryNode = doc.DocumentElement.SelectSingleNode("system.web/httpHandlers"); if (FactoryNode != null) { FactoryNode.ParentNode.RemoveChild(FactoryNode); } XmlNode RewriterNode = doc.DocumentElement.SelectSingleNode("system.web/httpModules"); if (RewriterNode != null) { RewriterNode.ParentNode.RemoveChild(RewriterNode); } } //IS6,IIS7下的system.web配置 if (version == IISVersion.IIS6 || version == IISVersion.IIS7) { //添加NFinal节点属性 XmlNode FactoryNode = doc.DocumentElement.SelectSingleNode("system.web/httpHandlers/add[@type='NFinal.Handler.HandlerFactory']"); //不存在则添加 if (FactoryNode == null) { changed = true; XmlNode handlersNode = CreateXMLPath(doc, "configuration/system.web/httpHandlers"); XmlNode NFinalHandlerNode = doc.CreateElement("add"); XmlAttribute attrVerb = doc.CreateAttribute("verb"); attrVerb.Value = "*"; XmlAttribute attrPath = doc.CreateAttribute("path"); attrPath.Value = "*.htm"; XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "NFinal.Handler.HandlerFactory"; NFinalHandlerNode.Attributes.RemoveAll(); NFinalHandlerNode.Attributes.Append(attrVerb); NFinalHandlerNode.Attributes.Append(attrPath); NFinalHandlerNode.Attributes.Append(attrType); handlersNode.AppendChild(NFinalHandlerNode); } //添加Rewriter节点属性 XmlNode RewriterNode = doc.DocumentElement.SelectSingleNode("system.web/httpModules/add[@type='NFinal.URLRewriter.ModuleRewriter']"); if (RewriterNode == null) { changed = true; XmlNode modulesNode = CreateXMLPath(doc, "configuration/system.web/httpModules"); XmlNode urlRewriterNode = doc.CreateElement("add"); XmlAttribute attrName = doc.CreateAttribute("name"); attrName.Value = "ModuleRewriter"; XmlAttribute attrType = doc.CreateAttribute("type"); attrType.Value = "NFinal.URLRewriter.ModuleRewriter"; urlRewriterNode.Attributes.Append(attrName); urlRewriterNode.Attributes.Append(attrType); modulesNode.AppendChild(urlRewriterNode); } //防止使用Rewriter的项目已经使用了别的URL重写模块 XmlNode rewriterModuleNode = doc.DocumentElement.SelectSingleNode("system.web/httpModules/add[@name='ModuleRewriter']"); if (rewriterModuleNode.Attributes["type"] != null) { if (rewriterModuleNode.Attributes["type"].Value.IndexOf(",") > -1) { changed = true; rewriterModuleNode.Attributes["type"].Value = "NFinal.URLRewriter.ModuleRewriter"; } } } //IIS6下要删除新的system.webServer的配置 if (version == IISVersion.IIS6) { XmlNode newWebServerNode = doc.DocumentElement.SelectSingleNode("system.webServer"); if (newWebServerNode != null) { newWebServerNode.ParentNode.RemoveChild(newWebServerNode); } } //如果文档变动就保存 if (changed) { doc.Save(webConfig); } return(Apps); }