static void SaveFile(string file) { using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { StringBuilder usb = new StringBuilder(); usb.AppendLineEx("//this source code was auto-generated by tolua#, do not modify it"); foreach (string str in usingList) { usb.AppendFormat("using {0};\r\n", str); } usb.AppendLineEx("using LuaInterface;"); if (ambig == ObjAmbig.All) { usb.AppendLineEx("using Object = UnityEngine.Object;"); } usb.AppendLineEx(); textWriter.Write(usb.ToString()); textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } }
static void CreateEmptyLuaBinder() { StringBuilder sb = new StringBuilder(); sb.AppendLineEx("using System;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tthrow new LuaException(\"Please generate LuaBinder files first!\");"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}"); string file = CustomSettings.saveDir + "/LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); }
public static void GenAngular2IndexTS(IEnumerable <TableSetting> tables, string outputPath) { var result = new StringBuilder(); foreach (var line in System.IO.File.ReadLines(System.IO.Path.Combine(outputPath, Angular2IndexTemplate))) { var trimmedEnd = line.TrimEnd(); var trimmed = trimmedEnd.TrimStart(); var baseTab = trimmedEnd.Substring(0, trimmedEnd.Length - trimmed.Length); if (trimmed == "<Imports>") { result.Append(Imports(tables, baseTab)); } else if (trimmed == "<Exports>") { result.Append(Exports(tables, baseTab)); } else if (trimmed == "<Declarations_exports>") { result.Append(Declarations_exports(tables, baseTab)); } else { result.AppendLineEx(line); } } FileUtils.WriteAllTextInUTF8(System.IO.Path.Combine(outputPath, "index.ts"), result.ToString()); }
private static string DataGridColumns(IEnumerable <ColumnSetting> columnSettings, string baseTab) { if (columnSettings.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); var tab1 = baseTab + Constant.Tab; foreach (var item in columnSettings) { var columnName = item.GetColumnNameForCodeGen(); if (columnName == "TenantID") { continue; } if (columnName == "CreateTime" || columnName == "LastUpdateTime") { sb.AppendLineExWithTabAndFormat(baseTab, "<SimpleDataGrid:DataGridTextColumnExt Header=\"{0}\" IsReadOnly=\"True\" Binding=\"{{Binding {0}, UpdateSourceTrigger=PropertyChanged, Converter={{x:Static converter:LongToDateTimeStringConverter.Instance}}}}\"/>", columnName); continue; } sb.AppendLineEx(GetDataGridColumnFromProperty(item, baseTab)); } return(sb.ToString()); }
public static void GenAngular2TestGenTS(IEnumerable <TableSetting> tables, string outputPath) { var result = new StringBuilder(); foreach (var line in System.IO.File.ReadLines(System.IO.Path.Combine(outputPath, Angular2TestGenTemplate))) { var trimmedEnd = line.TrimEnd(); var trimmed = trimmedEnd.TrimStart(); var baseTab = trimmedEnd.Substring(0, trimmedEnd.Length - trimmed.Length); if (trimmed == "<NgSwitchCases>") { result.Append(NgSwitchCases(tables, baseTab)); } else if (trimmed == "<DeclareItems>") { result.Append(DeclareItems(tables, baseTab)); } else { result.AppendLineEx(line); } } FileUtils.WriteAllTextInUTF8(System.IO.Path.Combine(outputPath, "test-gen.component.ts"), result.ToString()); }
private static string ForeignKeyPickerWindows(TableSetting tableSetting, string baseTab) { var columnSettings = tableSetting.ColumnSettings.Where(p => p.IsNeedNavigationData).OrderBy(p => p.Order); if (columnSettings.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); var tab1 = baseTab + Constant.Tab; foreach (var item in columnSettings) { var columnName = item.GetColumnNameForCodeGen(); if (columnName == "ID" || columnName == "TenantID" || columnName == "CreateTime" || columnName == "LastUpdateTime") { continue; } var lowerFirstCharColumnName = ToLowerFirstChar(columnName); var foreignKeyTableName = item.DbColumn.ForeignKeyTableName; var tableName = tableSetting.TableName; sb.AppendLineExWithTab(baseTab, $"<h-window [name]=\"'window_{lowerFirstCharColumnName}Of{tableName}'\" #{lowerFirstCharColumnName}Window [visible]=\"false\" [ngContent]=\"{lowerFirstCharColumnName}\" [hasOkButton]=\"true\" [hasCancelButton]=\"true\" [hasCloseButton]=\"false\" [width]=\"500\" [height]=\"200\">"); sb.AppendLineExWithTab(tab1, $"<app-{foreignKeyTableName} [name]=\"'view_{foreignKeyTableName}Of{tableName}'\" #{lowerFirstCharColumnName}></app-{foreignKeyTableName}>"); sb.AppendLineExWithTab(baseTab, "</h-window>"); sb.AppendLineEx(); } return(sb.ToString()); }
public static void GenDbContextAndEntitiesClass(IEnumerable <TableSetting> tables, string outputPath) { var result = new StringBuilder(); result.AppendLineEx("//user tepmlate tag <ModelBuilderConfigEFFull> to generate context class for EF Full, <ModelBuilderConfigEFCore> to generate context class for EF Core."); var classKeyword = " class "; var contextName = ""; foreach (var line in System.IO.File.ReadLines(System.IO.Path.Combine(outputPath, DbContextTemplateFileName))) { var indexOfClass = line.IndexOf(classKeyword); if (indexOfClass != -1) { var afterClassKeywordIndex = indexOfClass + classKeyword.Length; var nextSpaceIndex = line.IndexOf(' ', afterClassKeywordIndex); contextName = line.Substring(afterClassKeywordIndex, nextSpaceIndex - afterClassKeywordIndex); result.AppendLineEx(line); continue; } var trimmedEnd = line.TrimEnd(); var trimmed = trimmedEnd.TrimStart(); var baseTab = trimmedEnd.Substring(0, trimmedEnd.Length - trimmed.Length); if (trimmed == "<ModelBuilderConfigEFCore>") { result.Append(ModelBuilderConfigEFCore(tables, baseTab)); } else if (trimmed == "<ModelBuilderConfigEFFull>") { result.Append(ModelBuilderConfigEFFull(tables, baseTab)); } else if (trimmed == "<DbSetProperties>") { result.Append(DbSetProperties(tables, baseTab)); } else { result.AppendLineEx(line); } } FileUtils.DeleteAllFileEndWith(outputPath, FileNameSubFix); FileUtils.WriteAllTextInUTF8(System.IO.Path.Combine(outputPath, contextName + FileNameSubFix), result.ToString()); GenEntitiesClass(tables, outputPath); }
static void ClearLuaWraps() { string[] files = Directory.GetFiles(CustomSettings.saveDir, "*.cs", SearchOption.TopDirectoryOnly); for (int i = 0; i < files.Length; i++) { File.Delete(files[i]); } string filename = Path.GetFullPath(CustomSettings.saveBaseDir); if (!Directory.Exists(filename)) { Directory.CreateDirectory(filename); } ToLuaExport.Clear(); List <DelegateType> list = new List <DelegateType>(); ToLuaExport.GenDelegates(list.ToArray(), CustomSettings.saveBaseDir + "DelegateFactory.cs"); ToLuaExport.Clear(); StringBuilder sb = new StringBuilder(); sb.AppendLineEx("using System;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tthrow new LuaException(\"Please generate LuaBinder files first!\");"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}"); string file = CustomSettings.saveBaseDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); }
public static void GenTextManagerCode(IEnumerable <TableSetting> tables, string outputPath) { var result = new StringBuilder(); var classKeyword = " class "; var className = ""; foreach (var line in System.IO.File.ReadLines(System.IO.Path.Combine(outputPath, TextManagerTemplateFileName))) { var indexOfClass = line.IndexOf(classKeyword); if (indexOfClass != -1) { var afterClassKeywordIndex = indexOfClass + classKeyword.Length; var nextSpaceIndex = line.IndexOf(' ', afterClassKeywordIndex); if (nextSpaceIndex == -1) { className = line.Substring(afterClassKeywordIndex); } else { className = line.Substring(afterClassKeywordIndex, nextSpaceIndex - afterClassKeywordIndex); } result.AppendLineEx(line); continue; } var trimmedEnd = line.TrimEnd(); var trimmed = trimmedEnd.TrimStart(); var baseTab = trimmedEnd.Substring(0, trimmedEnd.Length - trimmed.Length); if (trimmed == "<TextStaticProperties>") { result.Append(TextStaticProperties(tables, baseTab)); } else if (trimmed == "<InitDefaultTextData>") { result.Append(InitDefaultTextData(tables, baseTab)); } else { result.AppendLineEx(line); } } FileUtils.WriteAllTextInUTF8(System.IO.Path.Combine(outputPath, className + TextManagerFileNameSubFix), result.ToString()); }
private static string InitHeaderFilters(IEnumerable <ColumnSetting> columns, string tableName, string baseTab) { if (columns.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); var tab1 = baseTab + Constant.Tab; var tab2 = tab1 + Constant.Tab; foreach (var item in columns) { var columnName = item.GetColumnNameForCodeGen(); var dataType = item.DbColumn.DataType; var headerFilterModelType = GetHeaderFilterModelType(item); if (headerFilterModelType == "HeaderComboBoxFilterModel") { var foreignKeyTableName = item.DbColumn.ForeignKeyTableName; sb.AppendLineExWithTabAndFormat(baseTab, "_{0}Filter = new HeaderComboBoxFilterModel(", columnName); sb.AppendLineExWithTabAndFormat(tab1, "TextManager.{0}_{1}, HeaderComboBoxFilterModel.ComboBoxFilter,", tableName, columnName); sb.AppendLineExWithTabAndFormat(tab1, "nameof({0}DataModel.{1}),", tableName, columnName); sb.AppendLineExWithTabAndFormat(tab1, "typeof({0}),", dataType); sb.AppendLineExWithTabAndFormat(tab1, "nameof({0}DataModel.DisplayText),", foreignKeyTableName); sb.AppendLineExWithTabAndFormat(tab1, "nameof({0}DataModel.ID))", foreignKeyTableName); sb.AppendLineExWithTab(baseTab, "{"); sb.AppendLineExWithTabAndFormat(tab1, "AddCommand = new SimpleCommand(\"{0}AddCommand\",", columnName); sb.AppendLineExWithTab(tab2, "() => base.ProccessHeaderAddCommand("); sb.AppendLineExWithTabAndFormat(tab2, "new View.{0}View(), \"{0}\", ReferenceDataManager<{0}Dto, {0}DataModel>.Instance.LoadOrUpdate)),", foreignKeyTableName); sb.AppendLineExWithTabAndFormat(tab1, "ItemSource = ReferenceDataManager<{0}Dto, {0}DataModel>.Instance.Get()", foreignKeyTableName); sb.AppendLineExWithTab(baseTab, "};"); } else if (headerFilterModelType == "HeaderForeignKeyFilterModel") { sb.AppendLineExWithTabAndFormat(baseTab, "_{0}Filter = new {1}(TextManager.{2}_{0}, nameof({2}DataModel.{0}), typeof({3}), new View.{4}View() {{ KeepSelectionType = DataGridExt.KeepSelection.KeepSelectedValue }});", columnName, headerFilterModelType, tableName, dataType, item.DbColumn.ForeignKeyTableName); } else { sb.AppendLineExWithTabAndFormat(baseTab, "_{0}Filter = new {1}(TextManager.{2}_{0}, nameof({2}DataModel.{0}), typeof({3}));", columnName, headerFilterModelType, tableName, dataType); } } sb.AppendLineEx(); foreach (var item in columns.Where(p => p.OrderBy != 0)) { var sortDirection = (item.OrderBy == 1) ? "Ascending" : "Descending"; sb.AppendLineExWithTabAndFormat(baseTab, "_{0}Filter.IsSorted = HeaderFilterBaseModel.SortDirection.{1};", item.GetColumnNameForCodeGen(), sortDirection); } return(sb.ToString()); }
public static string Exports(IEnumerable <TableSetting> tables, string baseTab) { var sb = new StringBuilder(); foreach (var item in tables) { sb.AppendLineEx($"export * from './{item.TableName}.component';"); } return(sb.ToString()); }
static void CreateDefaultWrapFile(string path, string name) { StringBuilder sb = new StringBuilder(); path = path + name + ".cs"; sb.AppendLineEx("using System;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class " + name); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Register(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tthrow new LuaException(\"Please click menu Lua/Gen BaseType Wrap first!\");"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}"); using (StreamWriter textWriter = new StreamWriter(path, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } }
public static string DeclareItems(IEnumerable <TableSetting> tables, string baseTab) { var sb = new StringBuilder(); sb.AppendTab(baseTab, "items = ["); foreach (var item in tables) { sb.Append($"'{item.TableName}', "); } sb.Remove(sb.Length - 2, 2); sb.AppendLineEx("];"); return(sb.ToString()); }
static void ClearLuaWraps() { string[] files = Directory.GetFiles(WrapFiles.saveDir, "*.cs", SearchOption.TopDirectoryOnly); for (int i = 0; i < files.Length; i++) { File.Delete(files[i]); } ToLuaExport.Clear(); List <DelegateType> list = new List <DelegateType>(); ToLuaExport.GenDelegates(list.ToArray()); ToLuaExport.Clear(); StringBuilder sb = new StringBuilder(); sb.AppendLineEx("using System;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}"); string file = WrapFiles.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); }
static void GenPreLoadFunction(BindType bt, StringBuilder sb) { string funcName = "LuaOpen_" + bt.wrapName; sb.AppendLineEx("\r\n\t[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); sb.AppendFormat("\tstatic int {1}{0}{2}(IntPtr L{3})\r\n", funcName, CustomNameSetting.functionPrefixName, CustomNameSetting.functionSuffixName, CustomNameSetting.variableSuffixName); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\ttry"); sb.AppendLineEx("\t\t{"); sb.AppendFormat("\t\t\tLuaState {0}state{1} = LuaState.Get(L{1});", CustomNameSetting.variablePrefixName, CustomNameSetting.variableSuffixName); sb.AppendFormat("\t\t\t{1}state{2}.BeginPreModule(\"{0}\");\r\n", bt.nameSpace, CustomNameSetting.variablePrefixName, CustomNameSetting.variableSuffixName); sb.AppendFormat("\t\t\t{1}{0}Wrap{2}.{3}Register{4}({5}state{6});\r\n", bt.wrapName, CustomNameSetting.classPrefixName, CustomNameSetting.classSuffixName, CustomNameSetting.functionPrefixName, CustomNameSetting.functionSuffixName, CustomNameSetting.variablePrefixName, CustomNameSetting.variableSuffixName); sb.AppendFormat("\t\t\tint {1}reference{2} = {1}state{2}.GetMetaReference(typeof({0}));\r\n", bt.name, CustomNameSetting.variablePrefixName, CustomNameSetting.variableSuffixName); sb.AppendFormat("\t\t\t{0}state{1}.EndPreModule(L{1}, {0}reference{1});", CustomNameSetting.variablePrefixName, CustomNameSetting.variableSuffixName); sb.AppendLineEx("\t\t\treturn 1;"); sb.AppendLineEx("\t\t}"); sb.AppendFormat("\t\tcatch(Exception {0}e{1})", CustomNameSetting.variablePrefixName, CustomNameSetting.variableSuffixName); sb.AppendLineEx("\t\t{"); sb.AppendFormat("\t\t\treturn LuaDLL.toluaL_exception(L{1}, {0}e{1});", CustomNameSetting.variablePrefixName, CustomNameSetting.variableSuffixName); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t}"); }
private static string HasChange(IEnumerable <ColumnSetting> columnSettings, string baseTab) { if (columnSettings.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); sb.AppendLineExWithTab(baseTab, "return"); foreach (var item in columnSettings) { sb.AppendLineExWithTabAndFormat(baseTab, "(o{0} != {0}) ||", item.GetColumnNameForCodeGen()); } var l = " ||".Length + Constant.LineEnding.Length; sb.Remove(sb.Length - l, l); sb.AppendLineEx(";"); return(sb.ToString()); }
private IEnumerator Do() { IEnumerator e = CollectExports(); while (e.MoveNext()) { yield return(null); } StringBuilder sb = new StringBuilder(); sb.AppendLineEx("-- this source code was auto-generated by pure lua, do not modify it"); sb.AppendLine("local this={}"); sb.AppendLine("local t"); e = ExportList(sb); while (e.MoveNext()) { yield return(null); } sb.AppendLine("return this"); EditorUtility.ClearProgressBar(); WriteFile(sb); }
private static string ForeignKeyDataModel(IEnumerable <ColumnSetting> columnSettings, string baseTab) { var foreignKeys = columnSettings.Where(p => p.DbColumn.IsForeignKey == true); if (foreignKeys.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); foreach (var item in foreignKeys) { sb.AppendLineExWithTabAndFormat(baseTab, "{0}DataModel _{1}Navigation;", item.DbColumn.ForeignKeyTableName, item.GetColumnNameForCodeGen()); } sb.AppendLineEx(); foreach (var item in foreignKeys) { sb.AppendLineExWithTabAndFormat(baseTab, "public {0}DataModel {1}Navigation {{ get {{ return _{1}Navigation; }} set {{ SetField(ref _{1}Navigation, value); }} }}", item.DbColumn.ForeignKeyTableName, item.GetColumnNameForCodeGen()); } return(sb.ToString()); }
private static string ReferenceDataSource(IEnumerable <ColumnSetting> columnSettings, string baseTab) { if (columnSettings.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); var foreignKeys = columnSettings.Where(p => p.DbColumn.IsForeignKey && p.IsNeedReferenceData); foreach (var item in foreignKeys) { sb.AppendLineExWithTabAndFormat(baseTab, "object _{0}DataSource;", item.GetColumnNameForCodeGen()); } sb.AppendLineEx(); foreach (var item in foreignKeys) { sb.AppendLineExWithTabAndFormat(baseTab, "public object {0}DataSource {{ get {{ return _{0}DataSource; }} set {{ SetField(ref _{0}DataSource, value); }} }}", item.GetColumnNameForCodeGen()); } return(sb.ToString()); }
private static string DataGridColumns(IEnumerable <ColumnSetting> columnSettings, string baseTab) { if (columnSettings.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); var tab1 = baseTab + Constant.Tab; foreach (var item in columnSettings) { var columnName = item.GetColumnNameForCodeGen(); if (columnName == "ID" || columnName == "TenantID" || columnName == "CreateTime" || columnName == "LastUpdateTime") { continue; } sb.AppendLineEx(GetDataGridColumnFromProperty(item, baseTab)); } return(sb.ToString()); }
static void GenLuaBinder() { if (!beAutoGen && EditorApplication.isCompiling) { EditorUtility.DisplayDialog("警告", "请等待编辑器完成编译在执行此功能", "确定"); return; } allTypes.Clear(); ToLuaTree<string> tree = InitTree(); StringBuilder sb = new StringBuilder(); sb.AppendLineEx("using System;"); sb.AppendLineEx("using UnityEngine;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tfloat t = Time.realtimeSinceStartup;"); sb.AppendLineEx("\t\tL.BeginModule(null);"); if (File.Exists(CustomSettings.saveDir + "DelegateFactoryWrap.cs")) { sb.AppendLineEx("\t\tDelegateFactoryWrap.Register(L);"); } for (int i = 0; i < allTypes.Count; i++) { if (allTypes[i].nameSpace == null) { string str = "\t\t" + allTypes[i].wrapName + "Wrap.Register(L);\r\n"; sb.Append(str); allTypes.RemoveAt(i--); } } Action<ToLuaNode<string>> begin = (node) => { if (node.value == null) { return; } sb.AppendFormat("\t\tL.BeginModule(\"{0}\");\r\n", node.value); string space = GetSpaceNameFromTree(node); for (int i =0; i < allTypes.Count; i++) { if (allTypes[i].nameSpace == space) { string str = "\t\t" + allTypes[i].wrapName + "Wrap.Register(L);\r\n"; sb.Append(str); allTypes.RemoveAt(i--); } } }; Action<ToLuaNode<string>> end = (node) => { if (node.value != null) { sb.AppendLineEx("\t\tL.EndModule();"); } }; tree.DepthFirstTraversal(begin, end, tree.GetRoot()); sb.AppendLineEx("\t\tL.EndModule();"); sb.AppendLineEx("\t\tDebugger.Log(\"Register lua type cost time: {0}\", Time.realtimeSinceStartup - t);"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}\r\n"); allTypes.Clear(); string file = CustomSettings.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); }
public static void ExtractFormattedStackTrace(StackTrace trace, StringBuilder sb, StackTrace skip = null) { int begin = 0; if (skip != null && skip.FrameCount > 0) { MethodBase m0 = skip.GetFrame(skip.FrameCount - 1).GetMethod(); for (int i = 0; i < trace.FrameCount; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); if (method == m0) { begin = i + 1; break; } } sb.AppendLineEx(); } for (int i = begin; i < trace.FrameCount; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); if (method == null || method.DeclaringType == null) { continue; } Type declaringType = method.DeclaringType; string str = declaringType.Namespace; if ((InstantiateCount == 0 && declaringType == typeof(UnityEngine.Object) && method.Name == "Instantiate") || //(method.Name == "Internal_CloneSingle" (SendMsgCount == 0 && declaringType == typeof(GameObject) && method.Name == "SendMessage")) { break; } if ((str != null) && (str.Length != 0)) { sb.Append(str); sb.Append("."); } sb.Append(declaringType.Name); sb.Append(":"); sb.Append(method.Name); sb.Append("("); int index = 0; ParameterInfo[] parameters = method.GetParameters(); bool flag = true; while (index < parameters.Length) { if (!flag) { sb.Append(", "); } else { flag = false; } sb.Append(parameters[index].ParameterType.Name); index++; } sb.Append(")"); string fileName = frame.GetFileName(); if (fileName != null) { fileName = fileName.Replace('\\', '/'); sb.Append(" (at "); if (fileName.StartsWith(projectFolder)) { fileName = fileName.Substring(projectFolder.Length, fileName.Length - projectFolder.Length); } sb.Append(fileName); sb.Append(":"); sb.Append(frame.GetFileLineNumber().ToString()); sb.Append(")"); } if (i != trace.FrameCount - 1) { sb.Append("\n"); } } }
static void GenLuaBinder() { if (!beAutoGen && EditorApplication.isCompiling) { EditorUtility.DisplayDialog("警告", "请等待编辑器完成编译在执行此功能", "确定"); return; } allTypes.Clear(); ToLuaTree <string> tree = InitTree(); StringBuilder sb = new StringBuilder(); List <DelegateType> dtList = new List <DelegateType>(); sb.AppendLineEx("using System;"); sb.AppendLineEx("using UnityEngine;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tfloat t = Time.realtimeSinceStartup;"); sb.AppendLineEx("\t\tL.BeginModule(null);"); //if (File.Exists(CustomSettings.saveDir + "DelegateFactoryWrap.cs")) //{ // sb.AppendLineEx("\t\tDelegateFactoryWrap.Register(L);"); //} for (int i = 0; i < allTypes.Count; i++) { if (allTypes[i].nameSpace == null) { string str = "\t\t" + allTypes[i].wrapName + "Wrap.Register(L);\r\n"; sb.Append(str); allTypes.RemoveAt(i--); } } Action <ToLuaNode <string> > begin = (node) => { if (node.value == null) { return; } sb.AppendFormat("\t\tL.BeginModule(\"{0}\");\r\n", node.value); string space = GetSpaceNameFromTree(node); for (int i = 0; i < allTypes.Count; i++) { if (allTypes[i].nameSpace == space) { string str = "\t\t" + allTypes[i].wrapName + "Wrap.Register(L);\r\n"; sb.Append(str); allTypes.RemoveAt(i--); } } string funcName = null; for (int i = 0; i < CustomSettings.customDelegateList.Length; i++) { DelegateType dt = CustomSettings.customDelegateList[i]; Type type = CustomSettings.customDelegateList[i].type; if (type.Namespace == space) { ToLuaExport.GetNameSpace(type, out funcName); funcName = ToLuaExport.ConvertToLibSign(funcName); string abr = dt.abr; abr = abr == null ? funcName : abr; sb.AppendFormat("\t\tL.RegFunction(\"{0}\", {1});\r\n", abr, dt.name); dtList.Add(dt); } } }; Action <ToLuaNode <string> > end = (node) => { if (node.value != null) { sb.AppendLineEx("\t\tL.EndModule();"); } }; tree.DepthFirstTraversal(begin, end, tree.GetRoot()); sb.AppendLineEx("\t\tL.EndModule();"); sb.AppendLineEx("\t\tDebugger.Log(\"Register lua type cost time: {0}\", Time.realtimeSinceStartup - t);"); sb.AppendLineEx("\t}"); for (int i = 0; i < dtList.Count; i++) { ToLuaExport.GenEventFunction(dtList[i].type, sb); } sb.AppendLineEx("}\r\n"); allTypes.Clear(); string file = CustomSettings.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); }
static void GenLuaBinder() { if (!beAutoGen && EditorApplication.isCompiling) { EditorUtility.DisplayDialog("警告", "请等待编辑器完成编译再执行此功能", "确定"); return; } allTypes.Clear(); ToLuaTree <string> tree = InitTree(); StringBuilder sb = new StringBuilder(); List <DelegateType> dtList = new List <DelegateType>(); List <DelegateType> list = new List <DelegateType>(); list.AddRange(CustomSettings.customDelegateList); // 以 HashSet<Type> 形式获取 CustomSettings.customTypeList 中所有委托类型元素(字段、属性、方法参数)的类型 HashSet <Type> set = GetCustomTypeDelegates(); // 以 List<BindType> 形式获取自身 allTypes 所有元素 List <BindType> backupList = new List <BindType>(); backupList.AddRange(allTypes); ToLuaNode <string> root = tree.GetRoot(); string libname = null; // 补充 List<DelegateType> list 中没有的 DelegateType foreach (Type t in set) { if (null == list.Find((p) => { return(p.type == t); })) { DelegateType dt = new DelegateType(t); AddSpaceNameToTree(tree, root, ToLuaExport.GetNameSpace(t, out libname)); list.Add(dt); } } // 拼接文本 sb.AppendLineEx("//this source code was auto-generated by tolua#, do not modify it"); sb.AppendLineEx("using System;"); sb.AppendLineEx("using UnityEngine;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tfloat t = Time.realtimeSinceStartup;"); sb.AppendLineEx("\t\tL.BeginModule(null);"); // 生成注册信息字符串并对 list、dtList 两个 list 做相应更新 GenRegisterInfo(null, sb, list, dtList); // 为 DepthFirstTraversal 方法新建一个将 value 不为空的 ToLuaNode<string> 的 value 组织字符串,并添加到参数 sb 中(于开头处添加字符);再获取参数 node 的完全限定名、根据 t 的 Namespace 更新参数 tree 和 root 的父或子节点信息 Action <ToLuaNode <string> > begin = (node) => { if (node.value == null) { return; } sb.AppendFormat("\t\tL.BeginModule(\"{0}\");\r\n", node.value); string space = GetSpaceNameFromTree(node); GenRegisterInfo(space, sb, list, dtList); }; // 为 DepthFirstTraversal 方法新建一个将 value 不为空的 ToLuaNode<string> 的 value 组织字符串并添加到参数 sb 中(于结尾处添加字符) Action <ToLuaNode <string> > end = (node) => { if (node.value != null) { sb.AppendLineEx("\t\tL.EndModule();"); } }; // 从最底层的子节点开始对参数 node 及其子节点进行遍历,同时使用 begin 和 end 委托对字符串进行修改 tree.DepthFirstTraversal(begin, end, tree.GetRoot()); // 在结尾处添加字符串 sb.AppendLineEx("\t\tL.EndModule();"); // 处理动态类型 list 字符串 if (CustomSettings.dynamicList.Count > 0) { sb.AppendLineEx("\t\tL.BeginPreLoad();"); for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t1 = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return(p.type == t1); }); sb.AppendFormat("\t\tL.AddPreLoad(\"{0}\", LuaOpen_{1}, typeof({0}));\r\n", bt.name, bt.wrapName); } sb.AppendLineEx("\t\tL.EndPreLoad();"); } sb.AppendLineEx("\t\tDebugger.Log(\"Register lua type cost time: {0}\", Time.realtimeSinceStartup - t);"); sb.AppendLineEx("\t}"); // 遍历 dtList,为每一个元素生成指定类型的 EventFunction 字符串并添加到参数 StringBuilder sb 中 for (int i = 0; i < dtList.Count; i++) { ToLuaExport.GenEventFunction(dtList[i].type, sb); } // 遍历动态类型 list 并为每一个 backupList 中类型与当前元素相等的 BindType 生成 PreLoadFunction 字符串并添加到参数 StringBuilder sb if (CustomSettings.dynamicList.Count > 0) { for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return(p.type == t); }); GenPreLoadFunction(bt, sb); } } // 添加结尾字符串,并清空 allTypes,合成文件储存路径 sb.AppendLineEx("}\r\n"); allTypes.Clear(); string file = CustomSettings.saveDir + "LuaBinder.cs"; // 生成文件、刷新 AssetDatabase 并打印提示 using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); Debugger.Log("Generate LuaBinder over !"); }
public static void Generate(string dir) { if (type.IsInterface && type != typeof(System.Collections.IEnumerator)) { return; } Debugger.Log("Begin Generate lua Wrap for class {0}", className); sb = new StringBuilder(); usingList.Add("System"); if (wrapClassName == "") { wrapClassName = className; } if (type.IsEnum) { GenEnum(); sb.AppendLineEx("}\r\n"); SaveFile(dir + wrapClassName + "Wrap.cs"); return; } List<MethodInfo> list = new List<MethodInfo>(); bool flag = false; if (baseType != null || isStaticClass) { binding |= BindingFlags.DeclaredOnly; flag = true; } list.AddRange(type.GetMethods(BindingFlags.Instance | binding)); for (int i = list.Count - 1; i >= 0; --i) { //去掉操作符函数 if (list[i].Name.StartsWith("op_") || list[i].Name.StartsWith("add_") || list[i].Name.StartsWith("remove_")) { if (!IsNeedOp(list[i].Name)) { list.RemoveAt(i); } continue; } //扔掉 unity3d 废弃的函数 if (IsObsolete(list[i])) { list.RemoveAt(i); } } PropertyInfo[] ps = type.GetProperties(); for (int i = 0; i < ps.Length; i++) { if (IsObsolete(ps[i])) { list.RemoveAll((p) => { return p == ps[i].GetGetMethod() || p == ps[i].GetSetMethod(); }); } else { MethodInfo md = ps[i].GetGetMethod(); if (md != null) { int index = list.FindIndex((m) => { return m == md; }); if (index >= 0) { if (md.GetParameters().Length == 0) { list.RemoveAt(index); } else if (md.Name == "get_Item") { getItems.Add(md); } } } md = ps[i].GetSetMethod(); if (md != null) { int index = list.FindIndex((m) => { return m == md; }); if (index >= 0) { if (md.GetParameters().Length == 1) { list.RemoveAt(index); } else if (md.Name == "set_Item") { setItems.Add(md); } } } } } if (flag && !isStaticClass) { List<MethodInfo> baseList = new List<MethodInfo>(type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase)); for (int i = baseList.Count - 1; i >= 0; i--) { if (BeDropMethodType(baseList[i])) { baseList.RemoveAt(i); } } HashSet<MethodInfo> addList = new HashSet<MethodInfo>(); for (int i = 0; i < list.Count; i++) { List<MethodInfo> mds = baseList.FindAll((p) => { return p.Name == list[i].Name; }); for(int j = 0; j < mds.Count; j++) { addList.Add(mds[j]); baseList.Remove(mds[j]); } } list.AddRange(addList); } for (int i = 0; i < list.Count; i++) { GetDelegateTypeFromMethodParams(list[i]); } ProcessExtends(list); GenBaseOpFunction(list); methods = list; InitPropertyList(); InitCtorList(); sb.AppendFormat("public class {0}Wrap\r\n", wrapClassName); sb.AppendLineEx("{"); GenRegisterFunction(); GenConstructFunction(); GenItemPropertyFunction(); GenFunctions(); GenToStringFunction(); GenIndexFunc(); GenNewIndexFunc(); GenOutFunction(); GenEventFunctions(); sb.AppendLineEx("}\r\n"); SaveFile(dir + wrapClassName + "Wrap.cs"); }
static void GenDelegateBody(StringBuilder sb, Type t, string head) { MethodInfo mi = t.GetMethod("Invoke"); ParameterInfo[] pi = mi.GetParameters(); int n = pi.Length; if (n == 0) { if (mi.ReturnType == typeof(void)) { sb.AppendFormat("{0}{{\r\n{0}\tfunc.Call();\r\n{0}}}\r\n", head); } else { sb.AppendFormat("{0}{{\r\n{0}\tfunc.Call();\r\n", head); GenLuaFunctionRetValue(sb, mi.ReturnType, head, "ret"); sb.AppendLineEx(head + "\treturn ret;"); sb.AppendFormat("{0}}}\r\n", head); } return; } sb.AppendFormat("{0}{{\r\n{0}", head); sb.AppendLineEx("\tfunc.BeginPCall();"); for (int i = 0; i < n; i++) { string push = GetPushFunction(pi[i].ParameterType); if (!IsParams(pi[i])) { if (pi[i].ParameterType == typeof(byte[]) && IsByteBuffer(t)) { sb.AppendFormat("{2}\tfunc.{0}(new LuaByteBuffer(param{1}));\r\n", push, i, head); } else { sb.AppendFormat("{2}\tfunc.{0}(param{1});\r\n", push, i, head); } } else { sb.AppendLineEx(); sb.AppendFormat("{0}\tfor (int i = 0; i < param{1}.Length; i++)\r\n", head, i); sb.AppendLineEx(head + "\t{"); sb.AppendFormat("{2}\t\tfunc.{0}(param{1}[i]);\r\n", push, i, head); sb.AppendLineEx(head + "\t}\r\n"); } } sb.AppendFormat("{0}\tfunc.PCall();\r\n", head); if (mi.ReturnType == typeof(void)) { for (int i = 0; i < pi.Length; i++) { if ((pi[i].Attributes & ParameterAttributes.Out) != ParameterAttributes.None) { GenLuaFunctionRetValue(sb, pi[i].ParameterType, head + "\t", "param" + i, true); } } sb.AppendFormat("{0}\tfunc.EndPCall();\r\n", head); } else { GenLuaFunctionRetValue(sb, mi.ReturnType, head + "\t", "ret"); for (int i = 0; i < pi.Length; i++) { if ((pi[i].Attributes & ParameterAttributes.Out) != ParameterAttributes.None) { GenLuaFunctionRetValue(sb, pi[i].ParameterType, head + "\t", "param" + i, true); } } sb.AppendFormat("{0}\tfunc.EndPCall();\r\n", head); sb.AppendLineEx(head + "\treturn ret;"); } sb.AppendFormat("{0}}}\r\n", head); }
static void GenLuaBinder() { if (!beAutoGen && EditorApplication.isCompiling) { EditorUtility.DisplayDialog("警告", "请等待编辑器完成编译再执行此功能", "确定"); return; } allTypes.Clear(); ToLuaTree <string> tree = InitTree(); StringBuilder sb = new StringBuilder(); List <DelegateType> dtList = new List <DelegateType>(); List <DelegateType> list = new List <DelegateType>(); list.AddRange(CustomSettings.customDelegateList); HashSet <Type> set = GetCustomTypeDelegates(); List <BindType> backupList = new List <BindType>(); backupList.AddRange(allTypes); ToLuaNode <string> root = tree.GetRoot(); string libname = null; foreach (Type t in set) { if (null == list.Find((p) => { return(p.type == t); })) { DelegateType dt = new DelegateType(t); AddSpaceNameToTree(tree, root, ToLuaExport.GetNameSpace(t, out libname)); list.Add(dt); } } sb.AppendLineEx("//this source code was auto-generated by tolua#, do not modify it"); sb.AppendLineEx("using System;"); sb.AppendLineEx("using UnityEngine;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tfloat t = Time.realtimeSinceStartup;"); sb.AppendLineEx("\t\tL.BeginModule(null);"); GenRegisterInfo(null, sb, list, dtList); Action <ToLuaNode <string> > begin = (node) => { if (node.value == null) { return; } sb.AppendFormat("\t\tL.BeginModule(\"{0}\");\r\n", node.value); string space = GetSpaceNameFromTree(node); GenRegisterInfo(space, sb, list, dtList); }; Action <ToLuaNode <string> > end = (node) => { if (node.value != null) { sb.AppendLineEx("\t\tL.EndModule();"); } }; tree.DepthFirstTraversal(begin, end, tree.GetRoot()); sb.AppendLineEx("\t\tL.EndModule();"); if (CustomSettings.dynamicList.Count > 0) { sb.AppendLineEx("\t\tL.BeginPreLoad();"); for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t1 = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return(p.type == t1); }); if (bt != null) { sb.AppendFormat("\t\tL.AddPreLoad(\"{0}\", LuaOpen_{1}, typeof({0}));\r\n", bt.name, bt.wrapName); } } sb.AppendLineEx("\t\tL.EndPreLoad();"); } sb.AppendLineEx("\t\tDebugger.Log(\"Register lua type cost time: {0}\", Time.realtimeSinceStartup - t);"); sb.AppendLineEx("\t}"); for (int i = 0; i < dtList.Count; i++) { ToLuaExport.GenEventFunction(dtList[i].type, sb); } if (CustomSettings.dynamicList.Count > 0) { for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return(p.type == t); }); if (bt != null) { GenPreLoadFunction(bt, sb); } } } sb.AppendLineEx("}\r\n"); allTypes.Clear(); string file = CustomSettings.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); Debugger.Log("Generate LuaBinder over !"); }
public static void ExtractFormattedStackTrace(StackTrace trace, StringBuilder sb, StackTrace skip = null) { int num = 0; if (skip != null && skip.get_FrameCount() > 0) { MethodBase method = skip.GetFrame(skip.get_FrameCount() - 1).GetMethod(); for (int i = 0; i < trace.get_FrameCount(); i++) { StackFrame frame = trace.GetFrame(i); MethodBase method2 = frame.GetMethod(); if (method2 == method) { num = i + 1; break; } } sb.AppendLineEx(string.Empty); } for (int j = num; j < trace.get_FrameCount(); j++) { StackFrame frame2 = trace.GetFrame(j); MethodBase method3 = frame2.GetMethod(); if (method3 != null && method3.get_DeclaringType() != null) { Type declaringType = method3.get_DeclaringType(); string @namespace = declaringType.get_Namespace(); if ((LuaException.InstantiateCount == 0 && declaringType == typeof(Object) && method3.get_Name() == "Instantiate") || (LuaException.SendMsgCount == 0 && declaringType == typeof(GameObject) && method3.get_Name() == "SendMessage")) { break; } if (@namespace != null && @namespace.get_Length() != 0) { sb.Append(@namespace); sb.Append("."); } sb.Append(declaringType.get_Name()); sb.Append(":"); sb.Append(method3.get_Name()); sb.Append("("); int k = 0; ParameterInfo[] parameters = method3.GetParameters(); bool flag = true; while (k < parameters.Length) { if (!flag) { sb.Append(", "); } else { flag = false; } sb.Append(parameters[k].get_ParameterType().get_Name()); k++; } sb.Append(")"); string text = frame2.GetFileName(); if (text != null) { text = text.Replace('\\', '/'); sb.Append(" (at "); if (text.StartsWith(LuaException.projectFolder)) { text = text.Substring(LuaException.projectFolder.get_Length(), text.get_Length() - LuaException.projectFolder.get_Length()); } sb.Append(text); sb.Append(":"); sb.Append(frame2.GetFileLineNumber().ToString()); sb.Append(")"); } if (j != trace.get_FrameCount() - 1) { sb.Append("\n"); } } } }
public static void ExtractFormattedStackTrace(StackTrace trace, StringBuilder sb, StackTrace skip = null) { int begin = 0; if (skip != null && skip.FrameCount > 0) { MethodBase m0 = skip.GetFrame(skip.FrameCount - 1).GetMethod(); for (int i = 0; i < trace.FrameCount; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); if (method == m0) { begin = i + 1; break; } } sb.AppendLineEx(); } for (int i = begin; i < trace.FrameCount; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); if (method == null || method.DeclaringType == null) { continue; } Type declaringType = method.DeclaringType; string str = declaringType.Namespace; if ( (InstantiateCount == 0 && declaringType == typeof(UnityEngine.Object) && method.Name == "Instantiate") //(method.Name == "Internal_CloneSingle" || (SendMsgCount == 0 && declaringType == typeof(GameObject) && method.Name == "SendMessage")) { break; } if ((str != null) && (str.Length != 0)) { sb.Append(str); sb.Append("."); } sb.Append(declaringType.Name); sb.Append(":"); sb.Append(method.Name); sb.Append("("); int index = 0; ParameterInfo[] parameters = method.GetParameters(); bool flag = true; while (index < parameters.Length) { if (!flag) { sb.Append(", "); } else { flag = false; } sb.Append(parameters[index].ParameterType.Name); index++; } sb.Append(")"); string fileName = frame.GetFileName(); if (fileName != null) { fileName = fileName.Replace('\\', '/'); sb.Append(" (at "); if (fileName.StartsWith(projectFolder)) { fileName = fileName.Substring(projectFolder.Length, fileName.Length - projectFolder.Length); } sb.Append(fileName); sb.Append(":"); sb.Append(frame.GetFileLineNumber().ToString()); sb.Append(")"); } if (i != trace.FrameCount - 1) { sb.Append("\n"); } } }
private static string ModelBuilderConfigEFCore(IEnumerable <TableSetting> tables, string baseTab) { if (tables.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); var tab1 = baseTab + Constant.Tab; var tab2 = tab1 + Constant.Tab; foreach (var table in tables) { var UpperedTableName = DatabaseUtils.UpperFirstLetter(table.TableName); sb.AppendLineExWithTabAndFormat(baseTab, "modelBuilder.Entity<{0}>(entity =>", UpperedTableName); sb.AppendLineExWithTab(baseTab, "{"); if (table.TableName != UpperedTableName) { sb.AppendLineExWithTabAndFormat(tab1, "entity.ToTable(\"{0}\");", table.TableName); sb.AppendLineEx(); } var pkColumn = table.ColumnSettings.First(p => p.DbColumn.IsIdentity); if (pkColumn.DbColumn.ColumnName != Constant.PrimaryKey) { sb.AppendLineExWithTabAndFormat(tab1, "entity.Property(p => p.ID).HasColumnName(\"{0}\");", pkColumn.DbColumn.ColumnName); sb.AppendLineEx(); } //foreach (var column in table.ColumnSettings.Where(p => p.IsReadOnly == true && p.DbColumn.IsIdentity == false && p.IsSmtColumn() == false)) //{ // sb.AppendLineExWithTabAndFormat(tab1, "entity.Property(p => p.{0}).ValueGeneratedOnAddOrUpdate();", column.ColumnName); // sb.AppendLineEx(); //} foreach (var index in table.DbTable.Indexes) { switch (index.IndexType) { case 0: sb.AppendLineExWithTabAndFormat(tab1, "entity.HasIndex(p => p.{0})", index.PropertyName); sb.AppendLineExWithTabAndFormat(tab2, ".HasName(\"{0}\");{1}", index.IX_Name); break; case 1: sb.AppendLineExWithTabAndFormat(tab1, "entity.HasKey(p => p.{0})", Constant.PrimaryKey); sb.AppendLineExWithTabAndFormat(tab2, ".HasName(\"{0}\");", index.IX_Name); break; case 2: sb.AppendLineExWithTabAndFormat(tab1, "entity.HasIndex(p => p.{0})", index.PropertyName); sb.AppendLineExWithTabAndFormat(tab2, ".HasName(\"{0}\")", index.IX_Name); sb.AppendLineExWithTab(tab2, ".IsUnique();"); break; } sb.AppendLineEx(); } foreach (var defaultValue in table.DbTable.DefaultValues) { var value = defaultValue.Value.Substring(1, defaultValue.Value.Length - 2); if (string.IsNullOrEmpty(value) == true) { value = "''"; } sb.AppendLineExWithTabAndFormat(tab1, "entity.Property(p => p.{0}).HasDefaultValueSql(\"{1}\");", defaultValue.PropertyName, value); sb.AppendLineEx(); } foreach (var hasColumnType in table.DbTable.HasColumnTypes) { sb.AppendLineExWithTabAndFormat(tab1, "entity.Property(p => p.{0}).HasColumnType(\"{1}\");", hasColumnType.PropertyName, hasColumnType.GetEFCoreColumnType()); } foreach (var requiredMaxLength in table.DbTable.RequiredMaxLengths) { sb.AppendTabAndFormat(tab1, "entity.Property(p => p.{0})", requiredMaxLength.PropertyName); if (requiredMaxLength.NeedIsRequired == true) { sb.AppendLineEx(); sb.AppendTab(tab2, ".IsRequired()"); } if (requiredMaxLength.MaxLength > 0) { sb.AppendLineEx(); sb.AppendTabAndFormat(tab2, ".HasMaxLength({0})", requiredMaxLength.MaxLength); } sb.AppendLineEx(";"); sb.AppendLineEx(); } foreach (var foreignKey in table.DbTable.ForeignKeys) { sb.AppendLineExWithTabAndFormat(tab1, "entity.HasOne(d => d.{0}Navigation)", foreignKey.PropertyName); sb.AppendLineExWithTabAndFormat(tab2, ".WithMany(p => p.{0}{1}Navigation)", UpperedTableName, foreignKey.PropertyName); sb.AppendLineExWithTabAndFormat(tab2, ".HasForeignKey(d => d.{0})", foreignKey.PropertyName); if (foreignKey.DeleteAction == 0) { sb.AppendLineExWithTab(tab2, ".OnDelete(DeleteBehavior.Restrict)"); } else if (foreignKey.DeleteAction == 1) { sb.AppendLineExWithTab(tab2, ".OnDelete(DeleteBehavior.SetNull)"); } else if (foreignKey.DeleteAction == 2) { sb.AppendLineExWithTab(tab2, ".OnDelete(DeleteBehavior.Cascade)"); } sb.AppendLineExWithTabAndFormat(tab2, ".HasConstraintName(\"{0}\");", foreignKey.FK_Name); sb.AppendLineEx(); } sb.Remove(sb.Length - Constant.LineEnding.Length, Constant.LineEnding.Length); sb.AppendLineExWithTab(baseTab, "});"); sb.AppendLineEx(); } sb.Remove(sb.Length - Constant.LineEnding.Length, Constant.LineEnding.Length); return(sb.ToString()); }
private static string ModelBuilderConfigEFFull(IEnumerable <TableSetting> tables, string baseTab) { if (tables.Count() == 0) { return(string.Empty); } var sb = new StringBuilder(); var tab1 = baseTab + Constant.Tab; var tab2 = tab1 + Constant.Tab; foreach (var table in tables) { var UpperedTableName = DatabaseUtils.UpperFirstLetter(table.TableName); var prefix = string.Format("modelBuilder.Entity<{0}>()", UpperedTableName); if (table.TableName != UpperedTableName) { sb.AppendLineExWithTabAndFormat(baseTab, "{0}.ToTable(\"{1}\");", prefix, table.TableName); } foreach (var index in table.DbTable.Indexes) { switch (index.IndexType) { case 0: sb.AppendLineExWithTabAndFormat(baseTab, "{0}.HasIndex(p => p.{1});", prefix, index.PropertyName); break; case 1: sb.AppendLineExWithTabAndFormat(baseTab, "{0}.HasKey(p => p.{1});", prefix, Constant.PrimaryKey); break; case 2: sb.AppendLineExWithTabAndFormat(baseTab, "{0}.HasIndex(p => p.{1}).IsUnique();", prefix, index.PropertyName); break; } } var pkColumn = table.ColumnSettings.First(p => p.DbColumn.IsIdentity); if (pkColumn.DbColumn.ColumnName != Constant.PrimaryKey) { sb.AppendLineExWithTabAndFormat(baseTab, "{0}.Property(p => p.ID).HasColumnName(\"{1}\");", prefix, pkColumn.DbColumn.ColumnName); } foreach (var hasColumnType in table.DbTable.HasColumnTypes) { sb.AppendLineExWithTabAndFormat(baseTab, "{0}.Property(p => p.{1}).HasColumnType(\"{2}\"){3};", prefix, hasColumnType.PropertyName, hasColumnType.TypeName, hasColumnType.GetEFFullColumnPrecision()); } foreach (var requiredMaxLength in table.DbTable.RequiredMaxLengths) { sb.AppendTabAndFormat(baseTab, "{0}.Property(p => p.{1})", prefix, requiredMaxLength.PropertyName); if (requiredMaxLength.NeedIsRequired == true) { sb.Append(".IsRequired()"); } if (requiredMaxLength.MaxLength > 0) { sb.AppendFormat(".HasMaxLength({0})", requiredMaxLength.MaxLength); } sb.AppendLineEx(";"); } foreach (var foreignKey in table.DbTable.ForeignKeys) { sb.AppendTabAndFormat(baseTab, "{0}.HasRequired(d => d.{1}Navigation)", prefix, foreignKey.PropertyName); sb.AppendFormat(".WithMany(p => p.{0}{1}Navigation)", UpperedTableName, foreignKey.PropertyName); sb.AppendFormat(".HasForeignKey(d => d.{0})", foreignKey.PropertyName); if (foreignKey.DeleteAction == 0) { sb.Append(".WillCascadeOnDelete(false)"); } else if (foreignKey.DeleteAction == 1) { //set null } else if (foreignKey.DeleteAction == 2) { sb.Append(".WillCascadeOnDelete(true)"); } sb.AppendLineEx(";"); } sb.AppendLineEx(); } sb.Remove(sb.Length - Constant.LineEnding.Length, Constant.LineEnding.Length); return(sb.ToString()); }
static void ClearLuaWraps() { string[] files = Directory.GetFiles(CustomSettings.saveDir, "*.cs", SearchOption.TopDirectoryOnly); for (int i = 0; i < files.Length; i++) { File.Delete(files[i]); } ToLuaExport.Clear(); List<DelegateType> list = new List<DelegateType>(); ToLuaExport.GenDelegates(list.ToArray()); ToLuaExport.Clear(); StringBuilder sb = new StringBuilder(); sb.AppendLineEx("using System;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}"); string file = CustomSettings.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); }
public static void Generate(string dir) { //if (type.IsInterface) //{ // return; //} Debugger.Log("Begin Generate lua Wrap for class {0}", className); sb = new StringBuilder(); usingList.Add("System"); if (wrapClassName == "") { wrapClassName = className; } if (type.IsEnum) { GenEnum(); sb.AppendLineEx("}\r\n"); SaveFile(dir + wrapClassName + "Wrap.cs"); return; } nameCounter = new Dictionary<string, int>(); List<MethodInfo> list = new List<MethodInfo>(); if (baseType != null || isStaticClass) { binding |= BindingFlags.DeclaredOnly; } list.AddRange(type.GetMethods(BindingFlags.Instance | binding)); for (int i = list.Count - 1; i >= 0; --i) { GetDelegateTypeFromMethodParams(list[i]); //先去掉操作符函数 if (list[i].Name.Contains("op_") || list[i].Name.Contains("add_") || list[i].Name.Contains("remove_")) { if (!IsNeedOp(list[i].Name)) { list.RemoveAt(i); } continue; } //扔掉 unity3d 废弃的函数 if (IsObsolete(list[i])) { list.RemoveAt(i); } } PropertyInfo[] ps = type.GetProperties(); for (int i = 0; i < ps.Length; i++) { int index = list.FindIndex((m) => { return m.Name == "get_" + ps[i].Name; }); if (index >= 0 && list[index].Name != "get_Item") { list.RemoveAt(index); } index = list.FindIndex((m) => { return m.Name == "set_" + ps[i].Name; }); if (index >= 0 && list[index].Name != "set_Item") { list.RemoveAt(index); } } ProcessExtends(list); GenBaseOpFunction(list); methods = list.ToArray(); sb.AppendFormat("public class {0}Wrap\r\n", wrapClassName); sb.AppendLineEx("{"); GenRegisterFunction(); GenConstructFunction(); GenTypeFunction(); GenFunctions(); GenToStringFunction(); GenIndexFunc(); GenNewIndexFunc(); GenOutFunction(); GenEventFunction(); sb.AppendLineEx("}\r\n"); //Debugger.Log(sb.ToString()); SaveFile(dir + wrapClassName + "Wrap.cs"); }
static void CreateDefaultWrapFile(string path, string name) { StringBuilder sb = new StringBuilder(); path = path + name + ".cs"; sb.AppendLineEx("using System;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class " + name); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Register(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}"); using (StreamWriter textWriter = new StreamWriter(path, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } }
static void GenLuaBinder() { if (!beAutoGen && EditorApplication.isCompiling) { EditorUtility.DisplayDialog("警告", "请等待编辑器完成编译再执行此功能", "确定"); return; } allTypes.Clear(); ToLuaTree<string> tree = InitTree(); StringBuilder sb = new StringBuilder(); List<DelegateType> dtList = new List<DelegateType>(); List<DelegateType> list = new List<DelegateType>(); list.AddRange(CustomSettings.customDelegateList); HashSet<Type> set = GetCustomTypeDelegates(); List<BindType> backupList = new List<BindType>(); backupList.AddRange(allTypes); ToLuaNode<string> root = tree.GetRoot(); foreach (Type t in set) { if (null == list.Find((p) => { return p.type == t; })) { DelegateType dt = new DelegateType(t); AddSpaceNameToTree(tree, root, dt.type.Namespace); list.Add(dt); } } sb.AppendLineEx("//this source code was auto-generated by tolua#, do not modify it"); sb.AppendLineEx("using System;"); sb.AppendLineEx("using UnityEngine;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tfloat t = Time.realtimeSinceStartup;"); sb.AppendLineEx("\t\tL.BeginModule(null);"); GenRegisterInfo(null, sb, list, dtList); Action<ToLuaNode<string>> begin = (node) => { if (node.value == null) { return; } sb.AppendFormat("\t\tL.BeginModule(\"{0}\");\r\n", node.value); string space = GetSpaceNameFromTree(node); GenRegisterInfo(space, sb, list, dtList); }; Action<ToLuaNode<string>> end = (node) => { if (node.value != null) { sb.AppendLineEx("\t\tL.EndModule();"); } }; tree.DepthFirstTraversal(begin, end, tree.GetRoot()); sb.AppendLineEx("\t\tL.EndModule();"); if (CustomSettings.dynamicList.Count > 0) { sb.AppendLineEx("\t\tL.BeginPreLoad();"); for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t1 = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return p.type == t1; }); sb.AppendFormat("\t\tL.AddPreLoad(\"{0}\", LuaOpen_{1}, typeof({0}));\r\n", bt.name, bt.wrapName); } sb.AppendLineEx("\t\tL.EndPreLoad();"); } sb.AppendLineEx("\t\tDebugger.Log(\"Register lua type cost time: {0}\", Time.realtimeSinceStartup - t);"); sb.AppendLineEx("\t}"); for (int i = 0; i < dtList.Count; i++) { ToLuaExport.GenEventFunction(dtList[i].type, sb); } if (CustomSettings.dynamicList.Count > 0) { for (int i = 0; i < CustomSettings.dynamicList.Count; i++) { Type t = CustomSettings.dynamicList[i]; BindType bt = backupList.Find((p) => { return p.type == t; }); GenPreLoadFunction(bt, sb); } } sb.AppendLineEx("}\r\n"); allTypes.Clear(); string file = CustomSettings.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); Debugger.Log("Generate LuaBinder over !"); }
static void GenPreLoadFunction(BindType bt, StringBuilder sb) { string funcName = "LuaOpen_" + bt.wrapName; sb.AppendLineEx("\r\n\t[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); sb.AppendFormat("\tstatic int {0}(IntPtr L)\r\n", funcName); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\ttry"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\tLuaState state = LuaState.Get(L);"); sb.AppendFormat("\t\t\tstate.BeginPreModule(\"{0}\");\r\n", bt.nameSpace); sb.AppendFormat("\t\t\t{0}Wrap.Register(state);\r\n", bt.wrapName); sb.AppendFormat("\t\t\tint reference = state.GetMetaReference(typeof({0}));\r\n", bt.name); sb.AppendLineEx("\t\t\tstate.EndPreModule(L, reference);"); sb.AppendLineEx("\t\t\treturn 1;"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t\tcatch(Exception e)"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\treturn LuaDLL.toluaL_exception(L, e);"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t}"); }
static void GenPreLoadFunction(BindType bt, StringBuilder sb) { string funcName = "LuaOpen_" + bt.wrapName; sb.AppendLineEx("\r\n\t[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); sb.AppendFormat("\tstatic int {0}(IntPtr L)\r\n", funcName); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\ttry"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\tLuaState state = LuaState.Get(L);"); sb.AppendFormat("\t\t\tint preTop = state.BeginPreModule(\"{0}\");\r\n", bt.nameSpace); sb.AppendFormat("\t\t\t{0}Wrap.Register(state);\r\n", bt.wrapName); sb.AppendLineEx("\t\t\tstate.EndPreModule(preTop);"); sb.AppendFormat("\t\t\tint reference = state.GetMetaReference(typeof({0}));\r\n", bt.name); sb.AppendLineEx("\t\t\tLuaDLL.lua_getref(L, reference);"); sb.AppendLineEx("\t\t\treturn 1;"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t\tcatch(Exception e)"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\treturn LuaDLL.toluaL_exception(L, e);"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t}"); }
public static void GenEventFunction(Type t, StringBuilder sb) { string funcName; string space = GetNameSpace(t, out funcName); funcName = CombineTypeStr(space, funcName); funcName = ConvertToLibSign(funcName); sb.AppendLineEx("\r\n\t[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); sb.AppendFormat("\tstatic int {0}(IntPtr L)\r\n", funcName); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\ttry"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\tint count = LuaDLL.lua_gettop(L);"); sb.AppendLineEx("\t\t\tLuaFunction func = ToLua.CheckLuaFunction(L, 1);"); sb.AppendLineEx(); sb.AppendLineEx("\t\t\tif (count == 1)"); sb.AppendLineEx("\t\t\t{"); sb.AppendFormat("\t\t\t\tDelegate arg1 = DelegateTraits<{0}>.Create(func);\r\n", GetTypeStr(t)); sb.AppendLineEx("\t\t\t\tToLua.Push(L, arg1);"); sb.AppendLineEx("\t\t\t}"); sb.AppendLineEx("\t\t\telse"); sb.AppendLineEx("\t\t\t{"); sb.AppendLineEx("\t\t\t\tLuaTable self = ToLua.CheckLuaTable(L, 2);"); sb.AppendFormat("\t\t\t\tDelegate arg1 = DelegateTraits<{0}>.Create(func, self);\r\n", GetTypeStr(t)); sb.AppendFormat("\t\t\t\tToLua.Push(L, arg1);\r\n"); sb.AppendLineEx("\t\t\t}"); sb.AppendLineEx("\t\t\treturn 1;"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t\tcatch(Exception e)"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\treturn LuaDLL.toluaL_exception(L, e);"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t}"); }
public static void GenEventFunction(Type t, StringBuilder sb) { string funcName; string space = GetNameSpace(t, out funcName); funcName = CombineTypeStr(space, funcName); funcName = ConvertToLibSign(funcName); sb.AppendLineEx("\r\n\t[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); sb.AppendFormat("\tstatic int {0}(IntPtr L)\r\n", funcName); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\ttry"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\tLuaFunction func = ToLua.CheckLuaFunction(L, 1);"); sb.AppendFormat("\t\t\tDelegate arg1 = DelegateFactory.CreateDelegate(typeof({0}), func);\r\n", GetTypeStr(t)); sb.AppendLineEx("\t\t\tToLua.Push(L, arg1);"); sb.AppendLineEx("\t\t\treturn 1;"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t\tcatch(Exception e)"); sb.AppendLineEx("\t\t{"); sb.AppendLineEx("\t\t\treturn LuaDLL.toluaL_exception(L, e);"); sb.AppendLineEx("\t\t}"); sb.AppendLineEx("\t}"); }
static void GenLuaBinder() { if (!beAutoGen && EditorApplication.isCompiling) { EditorUtility.DisplayDialog("警告", "请等待编辑器完成编译在执行此功能", "确定"); return; } allTypes.Clear(); ToLuaTree <string> tree = InitTree(); StringBuilder sb = new StringBuilder(); sb.AppendLineEx("using System;"); sb.AppendLineEx("using UnityEngine;"); sb.AppendLineEx("using LuaInterface;"); sb.AppendLineEx(); sb.AppendLineEx("public static class LuaBinder"); sb.AppendLineEx("{"); sb.AppendLineEx("\tpublic static void Bind(LuaState L)"); sb.AppendLineEx("\t{"); sb.AppendLineEx("\t\tfloat t = Time.realtimeSinceStartup;"); sb.AppendLineEx("\t\tL.BeginModule(null);"); if (File.Exists(WrapFiles.saveDir + "DelegateFactoryWrap.cs")) { sb.AppendLineEx("\t\tDelegateFactoryWrap.Register(L);"); } for (int i = 0; i < allTypes.Count; i++) { if (allTypes[i].nameSpace == null) { string str = "\t\t" + allTypes[i].wrapName + "Wrap.Register(L);\r\n"; sb.Append(str); allTypes.RemoveAt(i--); } } Action <ToLuaNode <string> > begin = (node) => { if (node.value == null) { return; } sb.AppendFormat("\t\tL.BeginModule(\"{0}\");\r\n", node.value); string space = GetSpaceNameFromTree(node); for (int i = 0; i < allTypes.Count; i++) { if (allTypes[i].nameSpace == space) { string str = "\t\t" + allTypes[i].wrapName + "Wrap.Register(L);\r\n"; sb.Append(str); allTypes.RemoveAt(i--); } } }; Action <ToLuaNode <string> > end = (node) => { if (node.value != null) { sb.AppendLineEx("\t\tL.EndModule();"); } }; tree.DepthFirstTraversal(begin, end, tree.GetRoot()); sb.AppendLineEx("\t\tL.EndModule();"); sb.AppendLineEx("\t\tDebugger.Log(\"Register lua type cost time: {0}\", Time.realtimeSinceStartup - t);"); sb.AppendLineEx("\t}"); sb.AppendLineEx("}\r\n"); allTypes.Clear(); string file = WrapFiles.saveDir + "LuaBinder.cs"; using (StreamWriter textWriter = new StreamWriter(file, false, Encoding.UTF8)) { textWriter.Write(sb.ToString()); textWriter.Flush(); textWriter.Close(); } AssetDatabase.Refresh(); }