static void Main(string[] args) { try { ConsoleCmdLine c = new ConsoleCmdLine(); CmdLineString srcDir = new CmdLineString("src", true, "源文件目录"); CmdLineString csharpDir = new CmdLineString("csharp", false, "生成C#文件的目录"); CmdLineString cppDir = new CmdLineString("cpp", false, "生成C++文件的目录"); CmdLineString nameSpace = new CmdLineString("ns", false, "命名空间"); c.RegisterParameter(srcDir); c.RegisterParameter(csharpDir); c.RegisterParameter(cppDir); c.RegisterParameter(nameSpace); c.Parse(args); ProtoResult result = Builder.BuildProto(srcDir); if (csharpDir.Exists) { Builder.GenCSharpFile(result, CodeGenHelper.InputDirHandle(csharpDir), nameSpace); } if (cppDir.Exists) { Builder.GenCppFile(result, CodeGenHelper.InputDirHandle(cppDir), nameSpace); } } catch (System.Exception ex) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.ResetColor(); Console.WriteLine("Please press any key to continue ... "); Console.ReadKey(); } }
public void GenCode(TableInfo tableInfo) { string tableName = tableInfo.TableName; string className = CodeGenHelper.GetClassName(tableName, cmc.CodeRule) + CodeGenRuleHelper.BSServer; string path = string.Format(@"{0}", "bsimpl.java.vm"); var dic = GetNVelocityVars(); dic.Add("tableInfo", tableInfo); dic.Add("bsPackage", cmc.BSPackage); dic.Add("wsPackage", cmc.WSPackage); dic.Add("codeRule", cmc.CodeRule); string str = nVelocityHelper.GenByTemplate(path, dic); string title = className + ".java"; if (cmc.IsShowGenCode) { CodeShow(title, str); } else { FileHelper.Write(cmc.OutPut + title, new[] { str }, SaveFileEncoding); } }
public void GenCode(TableInfo tableInfo) { string tableName = tableInfo.TableName; string className = CodeGenHelper.GetClassName(tableName, cmc.CodeRule); string path = string.Format(@"{0}", "model.cs.vm"); var dic = GetNVelocityVars(); dic.Add("tableInfo", tableInfo); dic.Add("modelNameSpace", cmc.ModelNameSpace); dic.Add("idalNameSpace", cmc.IDALNameSpace); dic.Add("dalNameSpace", cmc.DALNameSpace); dic.Add("bllNameSpace", cmc.BLLNameSpace); dic.Add("guiPluginName", cmc.PluginName); dic.Add("codeRule", cmc.CodeRule); string str = nVelocityHelper.GenByTemplate(path, dic); string title = className + ".cs"; if (cmc.IsShowGenCode) { CodeShow(title, str); } else { FileHelper.Write(cmc.OutPut + title, new[] { str }); } }
static private void addtosvcconfig() { try { string clrruntime = System.Reflection.Assembly.GetExecutingAssembly().ImageRuntimeVersion; string ComSvcConfigpath = ""; if (clrruntime.Contains("v2.")) { ComSvcConfigpath = @"%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ComSvcConfig.exe"; } else { ComSvcConfigpath = @"%windir%\Microsoft.NET\Framework\v4.0.30319\ComSvcConfig.exe"; } List <KeyValuePair <string, string> > objs = CodeGenHelper.GetclsidsfromAssembly(filename); foreach (var o in objs) { List <string> itfs = CodeGenHelper.GetinterfacesforclsidfromAssembly(filename, o.Key); foreach (var itf in itfs) { Process p = new Process(); p.StartInfo.FileName = System.Environment.ExpandEnvironmentVariables(ComSvcConfigpath); p.StartInfo.Arguments = String.Format("/install /application:{0} /contract:\"{1},{2}\" /hosting:complus /mex", appname, o.Key, itf); p.Start(); p.WaitForExit(); } } } catch { } }
void WriteTableCacheMembers(TextWriter writer) { var size = _data.Actions.ElementSize; writer.Write(" static "); writer.Write(size.Keyword); writer.WriteLine("[] GetTransitionTable()"); writer.WriteLine(" {"); if (_config.Manager.CacheTables) { writer.Write(" "); writer.Write(size.Keyword); writer.WriteLine("[] result;"); writer.WriteLine(); writer.WriteLine(" lock (_weakRef)"); writer.WriteLine(" {"); writer.Write(" if ((result = ("); writer.Write(size.Keyword); writer.WriteLine("[])_weakRef.Target) == null)"); writer.WriteLine(" {"); writer.Write(" _weakRef.Target = result = "); if (string.IsNullOrEmpty(_config.TableResourceName)) { CodeGenHelper.WriteLargeIntArray(writer, 5, 16, _data.Actions); } else { CodeGenHelper.WriteLargeIntArray(writer, _data.Actions.Method, _config.TableResourceName); } writer.WriteLine(";"); writer.WriteLine(" }"); writer.WriteLine(" }"); writer.WriteLine(); writer.WriteLine(" return result;"); writer.WriteLine(" }"); writer.WriteLine(); writer.WriteLine(" [DebuggerBrowsable(DebuggerBrowsableState.Never)]"); writer.WriteLine(" static readonly WeakReference _weakRef = new WeakReference(null);"); } else { writer.Write(" return "); if (string.IsNullOrEmpty(_config.TableResourceName)) { CodeGenHelper.WriteLargeIntArray(writer, 3, 16, _data.Actions); } else { CodeGenHelper.WriteLargeIntArray(writer, _data.Actions.Method, _config.TableResourceName); } writer.WriteLine(";"); writer.WriteLine(" }"); } }
protected override void BeforeQueryStatus(EventArgs e) { ThreadHelper.JoinableTaskFactory.Run(async() => { var project = await VS.Solutions.GetActiveProjectAsync(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var enabled = CodeGenHelper.IsCsOrVbProject(project); Command.Enabled = enabled; }); }
protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) { try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); System.Array solObjects = (Array)ApplicationObject.VisualStudioApplication.ActiveSolutionProjects; if (solObjects.Length < 1) { return; } Project project = (Project)solObjects.GetValue(0); if (!(CodeGenHelper.IsCsOrVbProject(project))) { return; } PersistentClassDialog pcd = new PersistentClassDialog(); pcd.ShowDialog(); if (pcd.Result == DialogResult.Cancel) { return; } SelectedItems selItems = ApplicationObject.VisualStudioApplication.SelectedItems; ProjectItem parentItem = null; if (selItems.Count == 1) { IEnumerator ienum = selItems.GetEnumerator(); ienum.MoveNext(); SelectedItem si = (SelectedItem)ienum.Current; if (si.ProjectItem != null && si.ProjectItem.Kind == "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}") // Folder { parentItem = si.ProjectItem; } } if (CodeGenHelper.IsVbProject(project)) { new AddPersistentClassVb(project, pcd.ClassName, pcd.Serializable, parentItem).DoIt(); } else if (CodeGenHelper.IsCsProject(project)) { new AddPersistentClassCs(project, pcd.ClassName, pcd.Serializable, parentItem).DoIt(); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); MessageBox.Show(ex.Message, "AddPersistentClass"); } }
void WriteTokenTable(TextWriter writer, int indent, ConfigTable table, string suffix) { CodeGenHelper.WriteIndent(writer, indent); writer.Write("_tokenTypes"); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.Write(" = new TokenType["); writer.Write(table.Graph.States.Count); writer.WriteLine(']'); CodeGenHelper.WriteIndent(writer, indent); writer.WriteLine('{'); var data = _stateData[table.Index]; var stateLabels = GetStateLabels(table.Graph, data); var typeLabels = new string[stateLabels.Length]; foreach (var state in table.Graph.States) { var endid = state.Label.EndState; typeLabels[data.StateMap[state]] = endid.HasValue ? _config.TokenTypes[endid.Value] : "EOF"; } for (var i = 0; i < typeLabels.Length; i++) { CodeGenHelper.WriteIndent(writer, indent + 1); writer.Write("TokenType."); writer.Write(typeLabels[i]); var label = stateLabels[i]; if (!string.IsNullOrEmpty(label)) { writer.Write(", // "); writer.Write(label); } else { writer.Write(','); } writer.WriteLine(); } CodeGenHelper.WriteIndent(writer, indent); writer.WriteLine("};"); }
static void WriteLargeCharArray(TextWriter writer, int indent, string name, string suffix, int wrap, IList <char> data) { CodeGenHelper.WriteIndent(writer, indent); writer.Write(name); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.Write(" = "); CodeGenHelper.WriteLargeCharArray(writer, indent, wrap, data); writer.WriteLine(";"); }
static void WriteLargeIntArray(TextWriter writer, int indent, string name, string suffix, Compression method, string tableResourseName) { CodeGenHelper.WriteIndent(writer, indent); writer.Write(name); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.Write(" = "); CodeGenHelper.WriteLargeIntArray(writer, method, tableResourseName); writer.WriteLine(";"); }
static void WriteLargeIntArray(TextWriter writer, int indent, string name, string suffix, int wrap, IList <int> data, ElementSizeStrategy elementSize) { CodeGenHelper.WriteIndent(writer, indent); writer.Write(name); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.Write(" = "); CodeGenHelper.WriteLargeIntArray(writer, indent, wrap, data, elementSize); writer.WriteLine(";"); }
public void DoIt() { try { StreamWriter sw; string fileName = Path.GetDirectoryName( project.FileName ) + "\\" + className + ".vb"; string partialFileName = fileName.Substring( 0, fileName.Length - 3 ); partialFileName += ".ndo.vb"; using (sw = new StreamWriter( fileName, false, System.Text.Encoding.UTF8 )) { sw.WriteLine( "Imports System.Linq" ); sw.WriteLine( "Imports System.Collections.Generic" ); sw.WriteLine( "Imports NDO\n" ); sw.WriteLine( "''' <summary>" ); sw.WriteLine( "'''" ); sw.WriteLine( "''' </summary>" ); sw.WriteLine( "''' <remarks></remarks>" ); sw.Write( "<NDOPersistent" ); if (isSerializable) sw.Write( ", Serializable" ); sw.WriteLine( "> _" ); sw.WriteLine( "Partial Public Class " + className ); sw.WriteLine( "End Class" ); } ProjectItem pi = null; if (parentItem == null) pi = project.ProjectItems.AddFromFile( fileName ); else pi = parentItem.ProjectItems.AddFromFile( fileName ); using (sw = new StreamWriter( partialFileName )) { string newPartial = partialTemplate.Replace( "#cl#", className ); sw.Write( newPartial ); } pi.ProjectItems.AddFromFile( partialFileName ); CodeGenHelper.ActivateAndGetTextDocument( project, Path.GetFileName( fileName ) ); } catch (Exception ex) { MessageBox.Show( ex.Message ); } }
public static void GenCSharpFile(ProtoResult result, string outDir, string nameSpace) { if (!Directory.Exists(outDir)) { Directory.CreateDirectory(outDir); } foreach (var entity in result.Enums) { string saveFile = Path.Combine(outDir, ProtoToCSharp.TypeToFileName(entity.Name.Value, nameSpace)); string code = ProtoToCSharp.EunmToFile(entity, nameSpace); CodeGenHelper.WriteFile(saveFile, code); } foreach (var entity in result.Structs) { string saveFile = Path.Combine(outDir, ProtoToCSharp.TypeToFileName(entity.Name.Value, nameSpace)); string code = ProtoToCSharp.StructToFile(entity, nameSpace); CodeGenHelper.WriteFile(saveFile, code); } }
public string GetSpringConfig(TableInfo tableInfo) { string tableName = tableInfo.TableName; string className = CodeGenHelper.GetClassName(tableName, cmc.CodeRule); string path = string.Format(@"{0}", "object.xml.vm"); var dic = GetNVelocityVars(); dic.Add("tableInfo", tableInfo); dic.Add("modelNameSpace", cmc.ModelNameSpace); dic.Add("idalNameSpace", cmc.IDALNameSpace); dic.Add("dalNameSpace", cmc.DALNameSpace); dic.Add("bllNameSpace", cmc.BLLNameSpace); dic.Add("guiPluginName", cmc.PluginName); dic.Add("codeRule", cmc.CodeRule); dic.Add("dalDllName", cmc.DALDllName); dic.Add("bllDllName", cmc.BLLDllName); string str = nVelocityHelper.GenByTemplate(path, dic); return(str); }
private void btnGenCode_Click(object sender, EventArgs e) { if (cmbType.Text != null) { switch (cmbType.Text) { case "": MessageBox.Show("请选择带转换文本所属类型"); break; case "Xml": textBox2.Text = CodeGenHelper.GenCSharpFromXml(textBox1.Text); break; case "Json": break; default: break; } } }
public Compiler(ILGenerator gen, SymbolTable symbolTable) { _bytecode = new global::VM.Bytecode(); _gen = gen; _symbolTable = symbolTable; _msilHelper = new CodeGenHelper(); _globals = _msilHelper.AllocArray <int[]>(_gen, 200); _stack = _msilHelper.AllocStack <int>(_gen); // Generic result variable for Pop, etc. _result = _gen.DeclareLocal(typeof(int)); // The tmp's are needed for storing values temporarily (mostly from/onto stack) _tmp1 = _gen.DeclareLocal(typeof(int)); _tmp2 = _gen.DeclareLocal(typeof(int)); _bp = _gen.DeclareLocal(typeof(int)); _labels = new Dictionary <int, Label>(); _errors = new List <IError>(); }
private void btnnew_Click(object sender, EventArgs e) { try { Program.UpdateStatus(""); OpenFileDialog ofd = new OpenFileDialog(); ofd.CheckFileExists = true; ofd.CheckPathExists = true; if (tabControl1.SelectedIndex == 3) { ofd.Filter = "Interfaces|*.cs"; } else { ofd.Filter = "Managed,Unmanaged,WSC|*.dll;*.tlb;*.Wsc"; } if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } { if (ofd.FileName.ToLower().Contains(".wsc")) { string sysdir = Environment.ExpandEnvironmentVariables((Environment.OSVersion.Version.Major > 5) ? @"%windir%\SysWOW64\" : @"%Windir%\system32\"); Process p = new Process(); p.StartInfo.FileName = sysdir + "regsvr32.exe"; p.StartInfo.Arguments = "/s " + '"' + ofd.FileName + '"'; p.Start(); p.WaitForExit(); string outputdir = txtoutput.Text + "\\tlb"; if (!Directory.Exists(outputdir)) { Directory.CreateDirectory(outputdir); } string tlbfile = outputdir + "\\" + System.IO.Path.ChangeExtension(Path.GetFileName(ofd.FileName), ".tlb"); p.StartInfo.FileName = sysdir + "RUNDLL32.EXE"; p.StartInfo.Arguments = string.Format("\"{0}scrobj.dll\",GenerateTypeLib -file:\"{1}\" \"{2}\"", sysdir, tlbfile, ofd.FileName); p.Start(); p.WaitForExit(); if (!File.Exists(tlbfile)) { Enabledisable(false); return; } ofd.FileName = tlbfile; } Enabledisable(true); txtprogid.Text = ""; txtpath.Text = ofd.FileName; cmbfiles.SelectedIndex = -1; bool bmanaged = true; List <KeyValuePair <string, string> > progclsidlst = CodeGenHelper.GetclsidsfromAssembly(txtpath.Text); if (progclsidlst.Count == 0) { progclsidlst = CodeGenHelper.GetclsidsfromTLB(txtpath.Text); bmanaged = false; } Program.UpdateStatus("# components found:" + progclsidlst.Count.ToString()); int sidx = -1; foreach (var kv in progclsidlst) { if (usersel.ContainsKey(kv.Key)) { continue; } sidx = cmbfiles.Items.Add(kv.Key); usersel.Add(kv.Key, new Comobjectstorage { path = txtpath.Text, clsid = new Guid(kv.Key), progid = kv.Value, bmanaged = bmanaged }); } if (sidx != -1) { cmbfiles.SelectedIndex = sidx; } } } catch (Exception ex) { Program.UpdateStatus(ex.Message); } }
public void DoIt() { try { StreamWriter sw; string fileName = Path.GetDirectoryName(project.FileName) + "\\" + className + ".cs"; string partialFileName = fileName.Substring(0, fileName.Length - 3); partialFileName += ".ndo.cs"; string namespc = (string)project.Properties.Item("RootNamespace").Value; using (sw = new StreamWriter(fileName, false, System.Text.Encoding.UTF8)) { StringBuilder sb = new StringBuilder(); sb.Append("using System;\n"); sb.Append("using System.Linq;\n"); sb.Append("using System.Collections.Generic;\n"); sb.Append("using NDO;\n\n"); sb.Append("namespace " + namespc + "\n"); sb.Append("{\n"); sb.Append("\t/// <summary>\n"); sb.Append("\t/// Summary for " + className + "\n"); sb.Append("\t/// </summary>\n"); sb.Append("\t[NDOPersistent"); if (this.isSerializable) { sb.Append(", Serializable"); } sb.Append("]\n"); sb.Append("\tpublic partial class " + className + "\n"); sb.Append("\t{\n"); sb.Append("\t\tpublic " + className + "()\n"); sb.Append("\t\t{\n"); sb.Append("\t\t}\n"); sb.Append("\t}\n"); sb.Append("}\n"); string result = sb.ToString(); TabProperty tp = TabProperties.Instance.CSharp; if (tp.UseSpaces) { sw.Write(result.Replace("\t", tp.Indent)); } else { sw.Write(result); } } ProjectItem pi = null; if (parentItem == null) { pi = project.ProjectItems.AddFromFile(fileName); } else { pi = parentItem.ProjectItems.AddFromFile(fileName); } using (sw = new StreamWriter(partialFileName)) { string newPartial = partialTemplate.Replace("#ns#", namespc); newPartial = newPartial.Replace("#cl#", className); sw.Write(newPartial); } pi.ProjectItems.AddFromFile(partialFileName); CodeGenHelper.ActivateAndGetTextDocument(project, Path.GetFileName(fileName)); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static string GetFileNameSafe(string fileName) { return(CodeGenHelper.GetSafeCodeName(Path.GetFileNameWithoutExtension(fileName))); }
public CsvDatabase CreateModel() { string[] files = FileUtils.EnumFiles(Properties.Files.Split('\n')); string baseDir = FileUtils.GetLongestCommonPrefixPath(files); //create db structure var db = new CsvDatabase() { Name = baseDir, Tables = ( from file in files where File.Exists(file) let csvSeparator = Properties.CsvSeparatorChar ?? FileUtils.CsvDetectSeparator(file) where !Properties.IgnoreInvalidFiles || FileUtils.CsvIsFormatValid(file, csvSeparator) let fileName = Path.GetFileName(file) let fileDir = (Path.GetDirectoryName(file.Remove(0, baseDir.Length) + "x") ?? "").TrimStart(Path.DirectorySeparatorChar) select new CsvTable() { FilePath = file, CodeName = CodeGenHelper.GetSafeCodeName(Path.GetFileNameWithoutExtension(fileName) + (string.IsNullOrWhiteSpace(fileDir) ? "" : ("_" + fileDir))), DisplayName = fileName + (string.IsNullOrWhiteSpace(fileDir) ? "" : (" in " + fileDir)) + " " + FileUtils.GetFileSizeInfo(file) + "", CsvSeparator = csvSeparator, Columns = ( from col in FileUtils.CsvReadHeader(file, csvSeparator).Select((value, index) => new { value, index }) select new CsvColumn() { CodeName = CodeGenHelper.GetSafeCodeName(col.value), DisplayName = "", CsvColumnName = col.value ?? "", CsvColumnIndex = col.index, } ).ToList(), } ).ToList(), }; //unique code names MakeCodeNamesUnique(db.Tables, t => t.CodeName, (t, n) => t.CodeName = n); foreach (var table in db.Tables) { MakeCodeNamesUnique(table.Columns, c => c.CodeName, (c, n) => c.CodeName = n); } //relations if (Properties.DetectRelations) { DetectRelations(db); foreach (var table in db.Tables) { MakeCodeNamesUnique(table.Relations, c => c.CodeName, (c, n) => c.CodeName = n, table.Columns.Select(c => c.CodeName)); } } //adjust displaynames foreach (var x in db.Tables) { x.DisplayName = x.CodeName + (string.IsNullOrWhiteSpace(x.DisplayName) ? "" : " (" + x.DisplayName + ")"); } foreach (var x in db.Tables.SelectMany(t => t.Columns)) { x.DisplayName = x.CodeName + (string.IsNullOrWhiteSpace(x.DisplayName) ? "" : " (" + x.DisplayName + ")"); } foreach (var x in db.Tables.SelectMany(t => t.Relations)) { x.DisplayName = x.CodeName + (string.IsNullOrWhiteSpace(x.DisplayName) ? "" : " (" + x.DisplayName + ")"); } return(db); }
public override void process(DataRow[] drTables, DataSet dsTableColumns, DataSet dsTablePrimaryKeys) { try { base.process(drTables, dsTableColumns, dsTablePrimaryKeys); OutPut = cmc.OutPut; setEnable(false); setStatusBar(""); if (drTables != null && dsTableColumns != null) { if (cmc.CodeRule == CodeGenRuleHelper.Ibatis) { CodeGenHelper.ReadConfig(cmc.Ibatis); } if (!cmc.IsShowGenCode) { FileHelper.DeleteDirectory(cmc.OutPut); setStatusBar(string.Format("正在生成{0}命名空间的Model", cmc.ModelNameSpace)); LogHelper.Info("Generating " + cmc.ModelNameSpace + " namespace model."); setProgreesEditValue(0); setProgress(0); setProgressMax(drTables.Length); } int j = 0; for (int i = 0; i < tableInfos.Count; i++) { string tableName = tableInfos[i].TableName; string[] temp = cmc.TableFilter.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries); bool flag = false; foreach (var str in temp) { if (tableName.StartsWith(str))//过滤 { flag = true; j++; break; } } if (!cmc.IsShowGenCode) { setStatusBar(string.Format("正在生成{0}命名空间中{1}信息,共{2}个Model,已生成了{3}个Model,过滤了{4}个Model", cmc.ModelNameSpace, CodeGenHelper.GetClassName(tableName, cmc.CodeRule), drTables.Length, i - j, j)); LogHelper.Info("Generationg in " + cmc.ModelNameSpace + " namespace " + CodeGenHelper.GetClassName(tableName, cmc.CodeRule) + " code, of " + drTables.Length + " codes, " + (i - j) + " of code has generated, " + j + " of code was filtered."); setProgress(1); } if (!flag) { GenCode(tableInfos[i]); } } } if (!cmc.IsShowGenCode) { setStatusBar(string.Format("{0}命名空间Model生成成功", cmc.ModelNameSpace)); LogHelper.Info(cmc.ModelNameSpace + " namespace code has generated success."); openDialog(); } } catch (Exception ex) { setStatusBar(string.Format("{0}命名空间Model生成失败[{1}]", cmc.ModelNameSpace, ex.Message)); LogHelper.Error(cmc.ModelNameSpace + " namespace code generated fail " + ex.Message); } finally { setEnable(true); } }
static void WriteTableFields(TextWriter writer, int indent, string suffix, ElementSizeStrategy elementSize, bool readOnly, bool @public) { CodeGenHelper.WriteIndent(writer, indent); writer.WriteLine("[DebuggerBrowsable(DebuggerBrowsableState.Never)]"); CodeGenHelper.WriteIndent(writer, indent); if (@public) { writer.Write("public "); } if (readOnly) { writer.Write("readonly "); } writer.Write("char[] _charClassificationBoundries"); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.WriteLine(";"); CodeGenHelper.WriteIndent(writer, indent); writer.WriteLine("[DebuggerBrowsable(DebuggerBrowsableState.Never)]"); CodeGenHelper.WriteIndent(writer, indent); if (@public) { writer.Write("public "); } if (readOnly) { writer.Write("readonly "); } writer.Write(elementSize.Keyword); writer.Write("[] _charClassification"); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.WriteLine(";"); CodeGenHelper.WriteIndent(writer, indent); writer.WriteLine("[DebuggerBrowsable(DebuggerBrowsableState.Never)]"); CodeGenHelper.WriteIndent(writer, indent); if (@public) { writer.Write("public "); } if (readOnly) { writer.Write("readonly "); } writer.Write(elementSize.Keyword); writer.Write("[] _transitionTable"); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.WriteLine(";"); CodeGenHelper.WriteIndent(writer, indent); writer.WriteLine("[DebuggerBrowsable(DebuggerBrowsableState.Never)]"); CodeGenHelper.WriteIndent(writer, indent); if (@public) { writer.Write("public "); } if (readOnly) { writer.Write("readonly "); } writer.Write("TokenType[] _tokenTypes"); if (!string.IsNullOrEmpty(suffix)) { writer.Write('_'); writer.Write(suffix); } writer.WriteLine(";"); }
private void GenerateCode() { if (ClassDataSource.Count > 0) { StringBuilder assemblyStringBuilder = new StringBuilder(); StringBuilder entityStringBuilder = null; assemblyStringBuilder.Append("using System;" + Environment.NewLine); assemblyStringBuilder.Append("using System.Collections.Generic;" + Environment.NewLine); //assemblyStringBuilder.Append("using System.Data;" + Environment.NewLine); assemblyStringBuilder.Append("using Rock.Orm.Common.Design;" + Environment.NewLine); assemblyStringBuilder.Append("namespace " + OutputNamespace + Environment.NewLine); assemblyStringBuilder.Append("{" + Environment.NewLine); string baseClassName = " : Rock.Orm.Common.Design.Entity"; foreach (var designClass in ClassDataSource) { entityStringBuilder = new StringBuilder(); //[Relation] if (designClass.MainType == 2) { entityStringBuilder.Append("[Relation]"); entityStringBuilder.Append(Environment.NewLine); } entityStringBuilder.Append("public interface " + designClass.ClassName + baseClassName); entityStringBuilder.Append(Environment.NewLine); entityStringBuilder.Append("{" + Environment.NewLine); designClass.Properties = ApplicationDesignService.GetClassDesignPropertyCollection(designClass.ClassID); foreach (var property in designClass.Properties) { //构造Atribute 结果 += " " + attrStr + CSharpDynClass.换行回车符; if (property.IsPrimarykey) { if (string.IsNullOrEmpty(property.StructName)) { entityStringBuilder.Append(" [PrimaryKey()]"); entityStringBuilder.Append(Environment.NewLine); } else { entityStringBuilder.Append(" [RelationKey(typeof(" + property.StructName + "))]"); entityStringBuilder.Append(Environment.NewLine); } } else { if (!property.IsNullable) { entityStringBuilder.Append(" [NotNull]"); entityStringBuilder.Append(Environment.NewLine); } } string dataType = string.Empty; switch (property.DataType) { case "String": dataType = "string"; if (property.DbFieldLength > 0) { entityStringBuilder.Append(" [SqlType(\"nvarchar(" + property.DbFieldLength + "\")]"); } else { entityStringBuilder.Append(" [SqlType(\"nvarchar(MAX\")]"); } entityStringBuilder.Append(Environment.NewLine); break; case "I32": if (property.IsNullable) { dataType = "int?"; } else { dataType = "int"; } break; case "Bool": if (property.IsNullable) { dataType = "bool?"; } else { dataType = "bool"; } break; case "DateTime": if (property.IsNullable) { dataType = "DateTime?"; } else { dataType = "DateTime"; } break; case "Decimal": entityStringBuilder.Append(" [SqlType(\"decimal(" + property.DbFieldLength + "," + property.DecimalDigits + "\")]"); entityStringBuilder.Append(Environment.NewLine); if (property.IsNullable) { dataType = "decimal?"; } else { dataType = "decimal"; } break; case "Struct": if (property.RelationType == "一对多") { entityStringBuilder.Append(" [FriendKey(typeof(" + property.StructName + "))]"); entityStringBuilder.Append(Environment.NewLine); entityStringBuilder.Append(" [FkReverseQuery(LazyLoad = true)]"); entityStringBuilder.Append(Environment.NewLine); entityStringBuilder.Append(" [MappingName(\"" + property.DbFieldName + "\")]"); entityStringBuilder.Append(Environment.NewLine); entityStringBuilder.Append(" [SerializationIgnore]"); entityStringBuilder.Append(Environment.NewLine); } else { if (designClass.MainType == 0) { entityStringBuilder.Append(" [FkQuery(\"" + designClass.ClassName + "ID\",LazyLoad = true)]"); entityStringBuilder.Append(Environment.NewLine); entityStringBuilder.Append(" [SerializationIgnore]"); entityStringBuilder.Append(Environment.NewLine); } } dataType = property.StructName; break; case "Binary": dataType = "byte[]"; break; case "I16": if (property.IsNullable) { dataType = "short?"; } else { dataType = "short"; } break; case "I64": if (property.IsNullable) { dataType = "long?"; } else { dataType = "long"; } break; case "Byte": if (property.IsNullable) { dataType = "byte?"; } else { dataType = "byte"; } break; case "Double": if (property.IsNullable) { dataType = "double?"; } else { dataType = "double"; } break; default: throw new Exception("数据类型错误:" + property.DataType); } switch (property.CollectionType) { case "None": if (property.DataType == "Struct") { entityStringBuilder.Append(" " + property.PropertyName + " " + property.PropertyName + " { get; set; }"); } else { entityStringBuilder.Append(" " + dataType + " " + property.PropertyName + " { get; set; }"); } break; case "List": entityStringBuilder.Append(" " + property.StructName + "[] " + property.PropertyName + " { get; set; }"); break; default: break; } entityStringBuilder.Append(Environment.NewLine); } entityStringBuilder.Append("}" + Environment.NewLine); assemblyStringBuilder.Append(entityStringBuilder.ToString()); } assemblyStringBuilder.Append("}"); Assembly ass = CSScript.LoadCode(assemblyStringBuilder.ToString()); CodeGenHelper codeGenHelper = new CodeGenHelper(OutputNamespace); EntityText = codeGenHelper.GenEntitiesEx(ass); } }
static void Main(string[] args) { bool slient = false; //args = new string[] { @"E:\QingdaoProject\Shumi.Qingdao.Design" }; if (args != null && args.Length > 0) { string designRootPath = args[0]; string configFile = Path.Combine(designRootPath, "EntityDesignConfig.xml"); try { XmlTextReader reader = new XmlTextReader(configFile); XmlSerializer serializer = new XmlSerializer(typeof(EntityDesignConfiguration)); EntityDesignConfiguration config = (EntityDesignConfiguration)serializer.Deserialize(reader); if (config != null) { Assembly ass = Assembly.LoadFrom(designRootPath + "\\bin\\" + config.CompileMode + "\\" + config.InputDllName); System.Text.Encoding encoding = System.Text.Encoding.Default; if (!string.IsNullOrEmpty(config.OutputCodeFileEncoding)) { encoding = System.Text.Encoding.GetEncoding(config.OutputCodeFileEncoding); } if (!string.IsNullOrEmpty(config.EntityCodePath)) { AdvOptForm adv = new AdvOptForm(); bool isDirectory; string entityCodePath = config.EntityCodePath; string filePath = ParseRelativePath(designRootPath, entityCodePath, out isDirectory); string fileBody = new CodeGenHelper(config.OutputNamespace, adv).GenEntitiesEx(ass, config.OutputLanguage.ToLower() == "c#" ? 0 : 1); if (Path.GetFileName(filePath) != string.Empty) { WriteFile(filePath, fileBody, encoding); } else { DirectoryInfo info = new DirectoryInfo(filePath); if (!info.Exists) info.Create(); //不存在,则创建目录 FileAttributes attribute = info.Attributes; if ((attribute & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { info.Attributes = attribute ^ FileAttributes.ReadOnly; } Type[] types = ass.GetTypes(); if (types != null) { List<Type> typelist = new List<Type>(types); typelist.RemoveAll(type => { return !type.IsInterface; }); string[] files = fileBody.Split(new string[] { "namespace", "Namespace" }, StringSplitOptions.RemoveEmptyEntries); IList<string> filelist = new List<string>(files); filelist.RemoveAt(0); Dictionary<string, string> dictTypeFiles = new Dictionary<string, string>(); for (int index = 0; index < typelist.Count; index++) { if (config.OutputLanguage.ToLower() == "c#") dictTypeFiles[typelist[index].Name] = "namespace" + filelist[index]; else dictTypeFiles[typelist[index].Name] = "Namespace" + filelist[index]; } if (dictTypeFiles.Count > 0) { foreach (string txtKey in dictTypeFiles.Keys) { string path = string.Format("{0}\\{1}.cs", filePath.TrimEnd('\\'), txtKey); WriteFile(path, dictTypeFiles[txtKey], encoding); } } } } } } slient = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } } if (!slient) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new EntityDesign()); } }
static private void performccreatecomappop(appoptions apopts) { try { bool bins = ((apopts & appoptions.install) != 0); bool bunins = ((apopts & appoptions.uninstall) != 0); bool bstart = ((apopts & appoptions.start) != 0); bool bstop = ((apopts & appoptions.stop) != 0); COMAdminCatalog catalog = new COMAdminCatalog(); COMAdminCatalogCollection applications = catalog.GetCollection("Applications") as COMAdminCatalogCollection; applications.Populate(); if (bins || bunins || bstart || bstop || breg) { for (int i = 0; i < applications.Count; ++i) { COMAdminCatalogObject app = applications.get_Item(i) as COMAdminCatalogObject; if (app.Name.ToString() == appname) { if (bstart) { catalog.StartApplication(appname); return; } catalog.ShutdownApplication(appname); if (bins || bunins) { applications.Remove(i); applications.SaveChanges(); } break; } } if (bins) { applications.Populate(); COMAdminCatalogObject application = applications.Add() as COMAdminCatalogObject; application.Value["ID"] = Guid.NewGuid().ToString("B"); application.Value["Name"] = appname; application.Value["RunForever"] = brunforever; applications.SaveChanges(); if (System.Environment.OSVersion.Version.Major > 5) { COMAdminCatalogCollection roles = (COMAdminCatalogCollection)applications.GetCollection("Roles", application.Key); roles.Populate(); COMAdminCatalogObject role = roles.Add() as COMAdminCatalogObject; role.Value["Name"] = "DefaultRole"; roles.SaveChanges(); COMAdminCatalogCollection users = (COMAdminCatalogCollection)roles.GetCollection("UsersInRole", role.Key); users.Populate(); COMAdminCatalogObject user = users.Add() as COMAdminCatalogObject; user.Value["User"] = "******"; users.SaveChanges(); } applications.SaveChanges(); } } if (breg || bunreg) { if (data.Count == 0) { if (filename == "") { ShowSyntax(); } List <KeyValuePair <string, string> > progclsidlst = new List <KeyValuePair <string, string> >(); if (filename.ToLower().IndexOf(".wsc") != -1) { progclsidlst = CodeGenHelper.GetclsidsfromWSC(filename); } else { progclsidlst = CodeGenHelper.GetclsidsfromAssembly(filename); if (progclsidlst.Count == 0) { progclsidlst = CodeGenHelper.GetclsidsfromTLB(filename); } } foreach (var kv in progclsidlst) { data.Add(kv.Key); } } foreach (string d in data) { if (breg) { catalog.ImportComponent(appname, d); } } } else if (bgac || bungac) { if (bgac) { catalog.InstallComponent(appname, filename, "", ""); } } applications.SaveChanges(); } catch { } }
public override void process(DataRow[] drTables, DataSet dsTableColumns, DataSet dsTablePrimaryKeys) { try { base.process(drTables, dsTableColumns, dsTablePrimaryKeys); //SaveFileEncoding = Encoding.GetEncoding("GBK"); CodeLanguage = "Java"; OutPut = cmc.OutPut; setEnable(false); setStatusBar(""); string[] strs = null; if (drTables != null && dsTableColumns != null) { if (cmc.CodeRule == CodeGenRuleHelper.Ibatis) { CodeGenHelper.ReadConfig(cmc.Ibatis); } if (!cmc.IsShowGenCode) { FileHelper.DeleteDirectory(cmc.OutPut); setStatusBar(string.Format("正在生成{0}包路径bs层代码", cmc.BSPackage)); LogHelper.Info("Generating " + cmc.BSPackage + " package path bs layer bs code."); setProgreesEditValue(0); setProgress(0); setProgressMax(drTables.Length); } int j = 0; for (int i = 0; i < tableInfos.Count; i++) { string tableName = tableInfos[i].TableName; string[] temp = cmc.TableFilter.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries); bool flag = false; foreach (var str in temp) { if (tableName.StartsWith(str))//过滤 { flag = true; j++; break; } } if (!cmc.IsShowGenCode) { setStatusBar(string.Format("正在生成{0}包路径bs中{1}的代码,共{2}个代码,已生成了{3}个代码,过滤了{4}个代码", cmc.BSPackage, CodeGenHelper.GetClassName(tableName, cmc.CodeRule) + CodeGenRuleHelper.BSServer, drTables.Length, i - j, j)); LogHelper.Info("Generating in " + cmc.BSPackage + " package path bs " + CodeGenHelper.GetClassName(tableName, cmc.CodeRule) + CodeGenRuleHelper.BSServer + " of code," + drTables.Length + " of codes," + (i - j) + "of code has generated," + j + " of code was filtered."); setProgress(1); } if (!flag) { GenCodeInterface(tableInfos[i]); GenCode(tableInfos[i]); } } } if (!cmc.IsShowGenCode) { setStatusBar(string.Format("{0}包路径bs代码生成成功", cmc.BSPackage)); LogHelper.Info(cmc.BSPackage + " package path bs code has generated success."); openDialog(); } } catch (Exception ex) { setStatusBar(string.Format("{0}包路径bs代码生成失败[{1}]", cmc.BSPackage, ex.Message)); LogHelper.Error(cmc.BSPackage + " package path bs code generated fail " + ex.Message); } finally { setEnable(true); } }
public void RefreshEntities(Type[] types) { checkEnableAdvOpt.Checked = false; listEntities.Items.Clear(); foreach (Type type in types) { if (typeof(NBear.Common.Design.Entity).IsAssignableFrom(type) && typeof(NBear.Common.Design.Entity) != type && CodeGenHelper.GetEntityAttribute <DraftAttribute>(type) == null) { listEntities.Items.Add(type.Name); } } }
public override void process(DataRow[] drTables, DataSet dsTableColumns, DataSet dsTablePrimaryKeys) { try { base.process(drTables, dsTableColumns, dsTablePrimaryKeys); CodeLanguage = "XML"; OutPut = cmc.OutPut; setStatusBar(""); setEnable(false); StringBuilder SqlMapConfig = new StringBuilder(); StringBuilder DAOContext = new StringBuilder(); StringBuilder WebServiceContext = new StringBuilder(); if (drTables != null && dsTableColumns != null) { if (cmc.CodeRule == CodeGenRuleHelper.Ibatis) { CodeGenHelper.ReadConfig(cmc.Ibatis); } if (!cmc.IsShowGenCode) { FileHelper.DeleteDirectory(cmc.OutPut); setStatusBar(string.Format("正在生成Spring配置文件")); LogHelper.Info("Generating spring configuration file."); setProgreesEditValue(0); setProgress(0); setProgressMax(drTables.Length); } int j = 0; for (int i = 0; i < tableInfos.Count; i++) { string tableName = tableInfos[i].TableName; string[] temp = cmc.TableFilter.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries); bool flag = false; foreach (var str in temp) { if (tableName.StartsWith(str))//过滤 { flag = true; j++; break; } } if (!cmc.IsShowGenCode) { setStatusBar(string.Format("正在生成Spring配置{0}的配置,共{1}个配置,已生成了{2}个配置,过滤了{3}个配置", tableName, drTables.Length, i - j, j)); LogHelper.Info("Generationg spring configuratin + " + tableName + "'s config, " + drTables.Length + " of configuration, " + (i - j) + " of configuration has generated, " + j + " of configuration was filtered."); setProgress(1); } if (!flag) { SqlMapConfig.Append(GenSqlMapConfig(tableInfos[i])); DAOContext.Append(GetDAOContext(tableInfos[i])); WebServiceContext.Append(GetWebServiceContext(tableInfos[i])); } } } if (!cmc.IsShowGenCode) { FileHelper.Write(cmc.OutPut + CodeGenRuleHelper.SqlMapConfig, new[] { SqlMapConfig.ToString() }); FileHelper.Write(cmc.OutPut + CodeGenRuleHelper.DAOContext, new[] { DAOContext.ToString() }); FileHelper.Write(cmc.OutPut + CodeGenRuleHelper.WebServiceContext, new[] { WebServiceContext.ToString() }); setStatusBar(string.Format("Spring配置生成成功")); LogHelper.Info("spring config has generated success."); openDialog(); } else { CodeShow(CodeGenRuleHelper.SqlMapConfig, SqlMapConfig.ToString()); CodeShow(CodeGenRuleHelper.DAOContext, DAOContext.ToString()); CodeShow(CodeGenRuleHelper.WebServiceContext, WebServiceContext.ToString()); } } catch (Exception ex) { setStatusBar(string.Format("Spring配置生成失败[{0}]", ex.Message)); LogHelper.Error("Spring config generated fail " + ex.Message); } finally { setEnable(true); } }