public Id(CodeFileBuilder builder) { _builder = builder; _column = new Column(_builder); _generatedBy = new GeneratedBy(_builder); _unsavedValue = new UnsavedValue(_builder); }
public void Start(string prefix, MappedPropertyInfo item) { CodeFileBuilder componentBuilder = new CodeFileBuilder(); componentBuilder.Indent(5); const string subPrefix = "y."; HbmCompositeElement component = item.HbmObject<HbmCompositeElement>(); componentBuilder.AddLine(""); var componentBodyBuilder = new ClassMapBody(componentBuilder); foreach (var componentPart in component.Items) { componentBodyBuilder.Add(subPrefix, new MappedPropertyInfo(componentPart, item.FileName)); } _builder.StartMethod(prefix, string.Format("{0}<{1}>(x => x.{2}, y=>", FluentNHibernateNames.CompositeElement, item.ReturnType, item.Name)); _builder.AddLine("{"); _builder.AddLine(componentBuilder.ToString()); _builder.AddLine("})"); /*if (component. ) { _builder.AddLine(string.Format(".{0}()", FluentNHibernateNames.Insert)); } if (component.update) { _builder.AddLine(string.Format(".{0}()", FluentNHibernateNames.Update)); }*/ }
public Bag(CodeFileBuilder builder) { _builder = builder; _orderBy = new OrderBy(builder); _cascade = new Cascade(builder); _inverse = new Inverse(builder); _table = new Table(builder); _keyColumn = new KeyColumn(builder); _lazyLoad = new LazyLoad(builder); }
public LazyLoad(CodeFileBuilder builder) { _builder = builder; }
public GeneratedBy(CodeFileBuilder builder) { _builder = builder; }
public Column(CodeFileBuilder builder) { _builder = builder; }
private bool Compile(string archivePath, string outputFile, ref string replacedFile, AssemblyInfo assemblyInfo) { bool allGood = false; #region Compile List <string> defines = new List <string>(); Dictionary <string, string> replacements = new Dictionary <string, string>(); #region Create the CodeDomProvider FileInfo fileInfo = new FileInfo(outputFile); if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } CodeDomProvider csc = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = true; cp.OutputAssembly = outputFile; cp.CompilerOptions = " /filealign:512 /optimize+ /platform:x86"; if (Helper.IsNotNullOrEmpty(IconFile)) { cp.CompilerOptions += string.Format(" /win32icon:\"{0}\"", IconFile); } if (Debug) { defines.Add("DEBUG"); cp.CompilerOptions += " /debug+ /debug:full"; } #endregion #region Defines defines.Add("RPX"); string targetName; ConsoleThemeColor targetColour = ConsoleThemeColor.SubTextGood; switch (ExecutableType) { case ExecutableType.Console: cp.CompilerOptions += " /target:exe"; targetName = Rpx.Strings.Compiler_ConsoleApplication; break; case ExecutableType.Forms: cp.CompilerOptions += " /target:winexe"; defines.Add("WinExec"); targetName = Rpx.Strings.Compiler_FormsApplication; break; default: cp.CompilerOptions += " /target:exe"; targetName = Rpx.Strings.Compiler_DefaultApplication; targetColour = ConsoleThemeColor.SubTextBad; break; } if (RC.ShouldWrite(ConsoleVerbosity.Verbose)) { RC.WriteLine(ConsoleVerbosity.Verbose, targetColour, " - " + string.Format(Rpx.Strings.Compiler_AssemblyTarget, targetName)); } else { RC.WriteLine(ConsoleVerbosity.Minimal, targetColour, " " + string.Format(Rpx.Strings.Compiler_AssemblyTarget, targetName)); } if (Decorate) { defines.Add("Decorate"); } if (Assemblys.Count > 1 || Tools.Count > 0) { defines.Add("HasAdditionalAssemblys"); } if (Tools.Count > 0) { defines.Add("IsToolkit"); } if (PassArguments) { defines.Add("PassArguments"); } if (GetAssembyInfoFrom != AssemblyInfoMode.SourceFile) { defines.Add("ExpliciteInfo"); replacements.Add("[Asm_Title]", Helper.MakeNonNull(assemblyInfo.Title)); string description = Helper.MakeNonNull(assemblyInfo.Description); if (Helper.IsNotNullOrEmpty(description)) // Asm_Description)) { description += "\n"; } string watermark = "RPX " + typeof(CompileProcess).Assembly.GetName().Version.ToString(); if (!description.Contains(watermark)) { description += watermark; } replacements.Add("[Asm_Description]", Helper.MakeNonNullAndEscape(description)); replacements.Add("[Asm_Configuration]", Helper.MakeNonNullAndEscape(assemblyInfo.Configuration)); replacements.Add("[Asm_Company]", Helper.MakeNonNullAndEscape(assemblyInfo.Company)); replacements.Add("[Asm_Product]", Helper.MakeNonNullAndEscape(assemblyInfo.Product)); replacements.Add("[Asm_Copyright]", Helper.MakeNonNullAndEscape(assemblyInfo.Copyright)); replacements.Add("[Asm_Trademark]", Helper.MakeNonNullAndEscape(assemblyInfo.Trademark)); replacements.Add("[Asm_Culture]", Helper.MakeNonNullAndEscape(assemblyInfo.Culture)); replacements.Add("[Asm_Version]", Helper.MakeNonNullAndEscape(assemblyInfo.Version)); replacements.Add("[Asm_FileVersion]", Helper.MakeNonNullAndEscape(assemblyInfo.FileVersion)); //RC.WriteLine(ConsoleVerbosity.Normal, ConsoleColorExt.Gray, " " + Rpx.Strings.Compiler_AssemblyInfoHasBeenReflected); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Product.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Product)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Version.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Version)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_FileVersion.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.FileVersion)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Configuration.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Configuration)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Company.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Company)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Description.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Description)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Copyright.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Copyright)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Trademark.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Trademark)); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Culture.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Culture)); } else { RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.Text, " " + Rpx.Strings.Compiler_AssemblyInfoFromFile); RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + AssembyInfoSourceFilePath); // } if (Compression.Protected) { if (Helper.IsNotNullOrEmpty(Compression.Password)) { RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.Text, " " + Rpx.Strings.Compiler_IncludeCryptographyCode); defines.Add("UseCryptography"); } else { RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.Text, " " + Rpx.Strings.Compiler_IncludeDisguiseCode); } defines.Add("Hidden"); } foreach (string define in defines) { cp.CompilerOptions += " /define:" + define; } #endregion #region Include the Archive Resource string archiveName = "a.zip"; if (Compression.Protected) { archiveName = "a"; } #region Finalise Package Compression.FinalisePackage(Compression.OutputFile); #endregion cp.CompilerOptions += string.Format(" /resource:\"{0}\",{1}", archivePath, archiveName); #endregion #region Add Default Refrences cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.CompilerOptions += string.Format(" /reference:\"{0}\"", typeof(Package).Assembly.Location); #endregion #region Define Remaining Code Template Replacements if (GetAssembyInfoFrom == AssemblyInfoMode.SourceFile) { replacements.Add("[#AssemblyInfo.cs#]", File.ReadAllText(AssembyInfoSourceFilePath).Replace("using System.Reflection;", "")); } replacements.Add("#ResourceLocation#", archiveName); if (Compression.Protected) { if (Helper.IsNotNullOrEmpty(Compression.Password)) { replacements.Add("[#PasswordVector#]", Helpers.EncryptHelper.InitVector); replacements.Add("[#PasswordSalt#]", Compression.SaltValue); replacements.Add("[#Password#]", Compression.Password); replacements.Add("[#PasswordStrength#]", "2"); } } List <Dictionary <string, string> > AssemblyReplacements = new List <Dictionary <string, string> >(); List <Dictionary <string, string> > ToolReplacements = new List <Dictionary <string, string> >(); #region Build Assembly Code int asmId = 0; if (Assemblys.Count > 1) { foreach (string asm in Assemblys) { string path = PackageHelper.MakeUriSafe(asm.Substring(asm.LastIndexOf("\\") + 1)); if (path != InitialAssemblyPath) { Dictionary <string, string> asmReplacements = new Dictionary <string, string>(); string idStr = "a" + (asmId++).ToString(); asmReplacements.Add("[#Asm_IdStr#]", idStr); asmReplacements.Add("[#Asm_Path#]", PackageHelper.MakeUriSafe(path)); AssemblyReplacements.Add(asmReplacements); } } } #endregion #region Build Tools Code if (Tools.Count > 0) { RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_Toolkit); if (RC.ShouldWrite(ConsoleVerbosity.Normal)) { RC.WriteLine(ConsoleVerbosity.Minimal, ConsoleThemeColor.Text, " " + string.Format(Rpx.Strings.Compiler_Tools, Tools.Count.ToString())); } else if (RC.ShouldWrite(ConsoleVerbosity.Minimal)) { RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.TitleText, " " + string.Format(Rpx.Strings.Compiler_Tools, Tools.Count.ToString())); RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText, " ("); } StringBuilder ToolsString = new StringBuilder(); bool firstMenu = true; foreach (KeyValuePair <string, string> tool in Tools) { string toolName = tool.Key; string asm = tool.Value; string path = PackageHelper.MakeUriSafe(asm.Substring(asm.LastIndexOf("\\") + 1)); if (path != InitialAssemblyPath) { Dictionary <string, string> asmReplacements = new Dictionary <string, string>(); Dictionary <string, string> toolReplacements = new Dictionary <string, string>(); string idStr = "a" + (asmId++).ToString(); asmReplacements.Add("[#Asm_IdStr#]", idStr); asmReplacements.Add("[#Asm_Path#]", PackageHelper.MakeUriSafe(path)); AssemblyReplacements.Add(asmReplacements); toolReplacements.Add("[#Tool_Name#]", toolName); toolReplacements.Add("[#Tool_Asm#]", idStr); ToolReplacements.Add(toolReplacements); if (RC.ShouldWrite(ConsoleVerbosity.Normal)) { RC.Write(ConsoleVerbosity.Normal, ConsoleThemeColor.SubText, " - " + toolName.PadRight(15, ' ') + " "); RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.SubText2, "(" + path + ")"); } else if (RC.ShouldWrite(ConsoleVerbosity.Minimal)) { if (!firstMenu) { RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText, ", "); } RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText2, toolName); firstMenu = false; } ToolsString.Append("\\n " + toolName); } } if (!RC.ShouldWrite(ConsoleVerbosity.Normal) && RC.ShouldWrite(ConsoleVerbosity.Minimal)) { RC.WriteLine(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText, ")"); } replacements.Add("[#ToolsString#]", ToolsString.ToString()); } #endregion replacements.Add("#InitialAssemblyPath#", PackageHelper.MakeUriSafe(InitialAssemblyPath)); #endregion #region Rename the Output File If It Exits So It Can Be Rolled Back if (File.Exists(outputFile)) { RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_BackupAsm); string name = new FileInfo(outputFile).Name; replacedFile = Application.UserAppDataPath + @"\" + Guid.NewGuid().GetHashCode().ToString() + "_" + name + ".InUse"; RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.Text, " " + replacedFile); File.Move(outputFile, replacedFile); } #endregion #region Compile Assembly From Code Template RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_Compiling); RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.Text, string.Format(" {0}: {1}", Rpx.Strings.Compiler_Options, cp.CompilerOptions.Replace("/", "\n /"))); CodeFileBuilder builder = GetCodeFileBuilderFromResource("Rpx.Packing.Embedded.RpxWrapperSource.xml"); Dictionary <string, List <Dictionary <string, string> > > ObjReplacements = new Dictionary <string, List <Dictionary <string, string> > >(); ObjReplacements.Add("Assemblys", AssemblyReplacements); ObjReplacements.Add("Tools", ToolReplacements); string source = builder.BuildCodeFile(replacements, ObjReplacements, defines); // Compile standalone executable with input files embedded as resource CompilerResults cr = csc.CompileAssemblyFromSource(cp, source); // yell if compilation error if (cr.Errors.Count > 0) { if (replacedFile != null) { File.Move(replacedFile, outputFile); replacedFile = null; } string msg = string.Format(Rpx.Strings.Compiler_BuildErrors, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { msg += Environment.NewLine + ce.ToString(); } if (!LogToConsole) { MessageBox.Show(msg); } else { RC.WriteError(02, string.Format(Rpx.Strings.Compiler_CompileFailed, cr.Errors.Count)); RC.WriteLine(ConsoleThemeColor.ErrorColor2, msg); if (RC.Verbosity == ConsoleVerbosity.Debug) { if (RC.IsBuildMode == false) { RC.Write(ConsoleThemeColor.SubTextBad, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth)); } else { RC.Write(ConsoleThemeColor.SubTextBad, new string('*', RC.BufferWidth)); } RC.WriteLine(); RC.WriteLine(ConsoleThemeColor.Text, source.Replace("\t", " ")); RC.WriteLine(); if (RC.IsBuildMode == false) { RC.Write(ConsoleThemeColor.SubTextBad, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth)); } else { RC.Write(ConsoleThemeColor.SubTextBad, new string('*', RC.BufferWidth)); } } } } else { if (RC.Verbosity == ConsoleVerbosity.Debug) { RC.Write(ConsoleThemeColor.SubTextGood, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth)); RC.WriteLine(); RC.WriteLine(ConsoleThemeColor.Text, source.Replace("\t", " ")); RC.WriteLine(); RC.Write(ConsoleThemeColor.SubTextGood, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth)); } FinalFileSize = new FileInfo(outputFile).Length; if (replacedFile != null) { File.SetAttributes(replacedFile, FileAttributes.Temporary); string junkFile = replacedFile.Substring(0, replacedFile.Length - 6) + ".junk"; RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_JunkingBackupAsm); RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.Text, " " + junkFile); File.Move(replacedFile, junkFile); replacedFile = null; } allGood = true; } #endregion #endregion return(allGood); }
public void BeforeEachTest() { _builder = new CodeFileBuilder(); _unsavedValue = new UnsavedValue(_builder); }
public void BeforeEachTest() { _builder = new CodeFileBuilder(); _customType = new CustomType(_builder); }
public Inverse(CodeFileBuilder builder) { _builder = builder; }
public void BeforeEachTest() { _builder = new CodeFileBuilder(); _column = new Column(_builder); }
public static void StartMethod(this CodeFileBuilder builder, string prefix, string methodBody) { builder.AddLine(prefix + methodBody); builder.Indent(); }
public Component(CodeFileBuilder builder) { _builder = builder; }
protected override void Generate( CodeWriter writer, EntityIdFactoryDescriptor descriptor, out string fileName, out string?path) { fileName = descriptor.Name; path = State; ClassBuilder classBuilder = ClassBuilder .New() .SetAccessModifier(AccessModifier.Public) .AddImplements(TypeNames.IEntityIdSerializer) .SetName(fileName); classBuilder .AddField(_options) .SetStatic() .SetReadOnly() .SetType(TypeNames.JsonWriterOptions) .SetValue(CodeBlockBuilder .New() .AddCode(MethodCallBuilder .Inline() .SetNew() .SetMethodName(TypeNames.JsonWriterOptions)) .AddCode(CodeInlineBuilder.From("{ Indented = false }"))); classBuilder .AddMethod("Parse") .SetAccessModifier(AccessModifier.Public) .SetReturnType(TypeNames.EntityId) .AddParameter(_obj, x => x.SetType(TypeNames.JsonElement)) .AddCode(ParseEntityIdBody(descriptor)); classBuilder .AddMethod("Format") .SetAccessModifier(AccessModifier.Public) .SetReturnType(TypeNames.String) .AddParameter(_entityId, x => x.SetType(TypeNames.EntityId)) .AddCode(FormatEntityIdBody(descriptor)); foreach (var entity in descriptor.Entities) { classBuilder .AddMethod($"Parse{entity.Name}EntityId") .SetAccessModifier(AccessModifier.Private) .SetReturnType(TypeNames.EntityId) .AddParameter(_obj, x => x.SetType(TypeNames.JsonElement)) .AddParameter(_type, x => x.SetType(TypeNames.String)) .AddCode(ParseSpecificEntityIdBody(entity)); classBuilder .AddMethod($"Format{entity.Name}EntityId") .SetAccessModifier(AccessModifier.Private) .SetReturnType(TypeNames.String) .AddParameter(_entityId, x => x.SetType(TypeNames.EntityId)) .AddCode(FormatSpecificEntityIdBody(entity)); } CodeFileBuilder .New() .SetNamespace(descriptor.Namespace) .AddType(classBuilder) .Build(writer); }
public void BeforEachTest() { _builder = new CodeFileBuilder(); _fetch = new Fetch(_builder); }
public References(CodeFileBuilder builder) { _builder = builder; _column = new Column(_builder); }
public OrderBy(CodeFileBuilder builder) { _builder = builder; }
public Unique(CodeFileBuilder builder) { _builder = builder; }
public override Task <CodeFile> GetCodeFileAsync(string originalName, Stream stream, bool runAnalysis) { return(Task.FromResult(CodeFileBuilder.Build(stream, runAnalysis))); }
protected override void Generate( CodeWriter writer, ITypeDescriptor typeDescriptor, out string fileName, out string?path) { ComplexTypeDescriptor descriptor = typeDescriptor as ComplexTypeDescriptor ?? throw new InvalidOperationException( "A result data factory can only be generated for complex types"); fileName = CreateResultFactoryName(descriptor.RuntimeType.Name); path = State; ClassBuilder classBuilder = ClassBuilder .New() .SetName(fileName) .AddImplements( TypeNames.IOperationResultDataFactory.WithGeneric(descriptor.RuntimeType)); ConstructorBuilder constructorBuilder = classBuilder .AddConstructor() .SetTypeName(descriptor.Name); AddConstructorAssignedField( TypeNames.IEntityStore, _entityStore, classBuilder, constructorBuilder); MethodCallBuilder returnStatement = MethodCallBuilder .New() .SetReturn() .SetNew() .SetMethodName(descriptor.RuntimeType.Name); foreach (PropertyDescriptor property in descriptor.Properties) { returnStatement .AddArgument(BuildMapMethodCall(_info, property)); } IfBuilder ifHasCorrectType = IfBuilder .New() .SetCondition( $"{_dataInfo} is {CreateResultInfoName(descriptor.RuntimeType.Name)} {_info}") .AddCode(returnStatement); classBuilder .AddMethod("Create") .SetAccessModifier(AccessModifier.Public) .SetReturnType(descriptor.RuntimeType.Name) .AddParameter(_dataInfo, b => b.SetType(TypeNames.IOperationResultDataInfo)) .AddParameter( _snapshot, b => b.SetDefault("null") .SetType(TypeNames.IEntityStoreSnapshot.MakeNullable())) .AddCode( IfBuilder.New() .SetCondition($"{_snapshot} is null") .AddCode( AssignmentBuilder .New() .SetLefthandSide(_snapshot) .SetRighthandSide($"{_entityStore}.CurrentSnapshot"))) .AddEmptyLine() .AddCode(ifHasCorrectType) .AddEmptyLine() .AddCode( ExceptionBuilder .New(TypeNames.ArgumentException) .AddArgument( $"\"{CreateResultInfoName(descriptor.RuntimeType.Name)} expected.\"")); var processed = new HashSet <string>(); AddRequiredMapMethods( _info, descriptor, classBuilder, constructorBuilder, processed, true); classBuilder .AddProperty("ResultType") .SetType(TypeNames.Type) .AsLambda($"typeof({descriptor.RuntimeType.Namespace}.{ descriptor.Implements[0]})") .SetInterface(TypeNames.IOperationResultDataFactory); classBuilder .AddMethod("Create") .SetInterface(TypeNames.IOperationResultDataFactory) .SetReturnType(TypeNames.Object) .AddParameter(_dataInfo, b => b.SetType(TypeNames.IOperationResultDataInfo)) .AddParameter( _snapshot, b => b.SetType(TypeNames.IEntityStoreSnapshot.MakeNullable())) .AddCode( MethodCallBuilder .New() .SetReturn() .SetMethodName("Create") .AddArgument(_dataInfo) .AddArgument(_snapshot)); CodeFileBuilder .New() .SetNamespace(CreateStateNamespace(descriptor.RuntimeType.NamespaceWithoutGlobal)) .AddType(classBuilder) .Build(writer); }
public Nullability(CodeFileBuilder builder) { _builder = builder; }
public Fetch(CodeFileBuilder builder) { _builder = builder; }
public void BeforeEachTest() { _builder = new CodeFileBuilder(); _table = new Table(_builder); }
public void BeforeEachTest() { _builder = new CodeFileBuilder(); _index = new Index(_builder); }
public KeyColumn(CodeFileBuilder builder) { _builder = builder; }
public Length(CodeFileBuilder builder) { _builder = builder; }
public CustomType(CodeFileBuilder builder) { _builder = builder; }
public Map(CodeFileBuilder builder) { _builder = builder; _length = new Length(_builder); _customType = new CustomType(_builder); }
private void ParseReferenceSourceFile(object state) { string fileName = state as string; if (string.IsNullOrEmpty(fileName)) { return; } try { if (!File.Exists(fileName)) { return; } string sourceText = File.ReadAllText(fileName); var inputStream = new ANTLRStringStream(sourceText, fileName); var unicodeStream = new JavaUnicodeStream(inputStream); var lexer = new Java2Lexer(unicodeStream); var tokenStream = new CommonTokenStream(lexer); var parser = new Java2Parser(tokenStream); int[] lineOffsets = null; var outputWindow = OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense); List <ParseErrorEventArgs> errors = new List <ParseErrorEventArgs>(); parser.ParseError += (sender, e) => { errors.Add(e); string message = e.Message; if (message.Length > 100) { message = message.Substring(0, 100) + " ..."; } if (lineOffsets == null) { lineOffsets = FindLineOffsets(sourceText); } int line = Array.BinarySearch(lineOffsets, e.Span.Start); if (line < 0) { line = -line - 2; } int column; if (line >= lineOffsets.Length) { column = 0; } else { column = e.Span.Start - lineOffsets[line]; } if (outputWindow != null) { outputWindow.WriteLine(string.Format("{0}({1},{2}): {3}", fileName, line + 1, column + 1, message)); } if (errors.Count > 20) { throw new OperationCanceledException(); } }; var result = parser.compilationUnit(); CodeFileBuilder fileBuilder = new CodeFileBuilder(fileName); var treeNodeStream = new CommonTreeNodeStream(result.Tree); treeNodeStream.TokenStream = tokenStream; var walker = new IntelliSenseCacheWalker(treeNodeStream); List <ParseErrorEventArgs> walkerErrors = new List <ParseErrorEventArgs>(); walker.ParseError += (sender, e) => { walkerErrors.Add(e); string message = e.Message; if (message.Length > 100) { message = message.Substring(0, 100) + " ..."; } if (lineOffsets == null) { lineOffsets = FindLineOffsets(sourceText); } int line = Array.BinarySearch(lineOffsets, e.Span.Start); if (line < 0) { line = -line - 2; } int column; if (line >= lineOffsets.Length) { column = 0; } else { column = e.Span.Start - lineOffsets[line]; } if (outputWindow != null) { outputWindow.WriteLine(string.Format("{0}({1},{2}): {3}", fileName, line + 1, column + 1, message)); } if (walkerErrors.Count > 20) { throw new OperationCanceledException(); } }; walker.compilationUnit(fileBuilder); UpdateFile(fileBuilder); } catch (Exception e) { if (ErrorHandler.IsCriticalException(e)) { throw; } } }
public CompositeElement(CodeFileBuilder builder) { _builder = builder; }
private void UpdateFile(CodeFileBuilder fileBuilder) { Contract.Requires(fileBuilder != null); CodeElement fileElement = fileBuilder.BuildElement(null); CodePhysicalFile file = fileElement as CodePhysicalFile; if (file == null) { throw new NotSupportedException(); } CodeElement[] elementsToAdd = file.GetDescendents(true).ToArray(); // apply changes to the cache using (_updateLock.WriteLock()) { CodePhysicalFile existingFile; if (_files.TryGetValue(file.FullName, out existingFile)) { // remove the file CodeElement[] elementsToRemove = existingFile.GetDescendents(true).ToArray(); foreach (var type in elementsToRemove.OfType <CodeType>()) { _types[type.Name].Remove(type); } string previousPackage = string.Empty; CodePackageStatement previousPackageStatement = elementsToRemove.OfType <CodePackageStatement>().FirstOrDefault(); if (previousPackageStatement != null) { previousPackage = previousPackageStatement.FullName; } _packages[previousPackage].Remove(existingFile); _packagesIgnoreCase[previousPackage].Remove(existingFile); _files.Remove(existingFile.FullName); } // now add the new file foreach (var type in elementsToAdd.OfType <CodeType>()) { HashSet <CodeType> types; if (!_types.TryGetValue(type.Name, out types)) { types = new HashSet <CodeType>(CodeElementLocationEqualityComparer.Default); _types.Add(type.Name, types); } types.Add(type); } string package = string.Empty; CodePackageStatement packageStatement = elementsToAdd.OfType <CodePackageStatement>().FirstOrDefault(); if (packageStatement != null) { package = packageStatement.FullName; } HashSet <CodePhysicalFile> packageFiles; if (!_packages.TryGetValue(package, out packageFiles)) { packageFiles = new HashSet <CodePhysicalFile>(ObjectReferenceEqualityComparer <CodePhysicalFile> .Default); _packages.Add(package, packageFiles); } packageFiles.Add(file); if (!_packagesIgnoreCase.TryGetValue(package, out packageFiles)) { packageFiles = new HashSet <CodePhysicalFile>(ObjectReferenceEqualityComparer <CodePhysicalFile> .Default); _packagesIgnoreCase.Add(package, packageFiles); } packageFiles.Add(file); _files.Add(file.FullName, file); } }
protected override void Generate( CodeWriter writer, ITypeDescriptor typeDescriptor, out string fileName, out string?path) { // Setup class ComplexTypeDescriptor descriptor = typeDescriptor as ComplexTypeDescriptor ?? throw new InvalidOperationException( "A result entity mapper can only be generated for complex types"); fileName = descriptor.ExtractMapperName(); path = State; ClassBuilder classBuilder = ClassBuilder .New() .AddImplements( TypeNames.IEntityMapper .WithGeneric( descriptor.ExtractType().ToString(), descriptor.RuntimeType.Name)) .SetName(fileName); ConstructorBuilder constructorBuilder = ConstructorBuilder .New() .SetTypeName(descriptor.Name); AddConstructorAssignedField( TypeNames.IEntityStore, StoreFieldName, classBuilder, constructorBuilder); // Define map method MethodBuilder mapMethod = MethodBuilder .New() .SetName(_map) .SetAccessModifier(AccessModifier.Public) .SetReturnType(descriptor.RuntimeType.Name) .AddParameter( ParameterBuilder .New() .SetType( descriptor.Kind == TypeKind.EntityType ? CreateEntityType( descriptor.Name, descriptor.RuntimeType.NamespaceWithoutGlobal) .ToString() : descriptor.Name) .SetName(_entity)) .AddParameter( _snapshot, b => b.SetDefault("null") .SetType(TypeNames.IEntityStoreSnapshot.MakeNullable())); mapMethod .AddCode(IfBuilder .New() .SetCondition($"{_snapshot} is null") .AddCode(AssignmentBuilder .New() .SetLefthandSide(_snapshot) .SetRighthandSide($"{_entityStore}.CurrentSnapshot"))) .AddEmptyLine(); MethodCallBuilder constructorCall = MethodCallBuilder .New() .SetReturn() .SetNew() .SetMethodName(descriptor.RuntimeType.Name); if (typeDescriptor is ComplexTypeDescriptor complexTypeDescriptor) { foreach (PropertyDescriptor property in complexTypeDescriptor.Properties) { constructorCall.AddArgument(BuildMapMethodCall(_entity, property)); } } mapMethod.AddCode(constructorCall); if (constructorBuilder.HasParameters()) { classBuilder.AddConstructor(constructorBuilder); } classBuilder.AddMethod(mapMethod); AddRequiredMapMethods( _entity, descriptor, classBuilder, constructorBuilder, new HashSet <string>()); CodeFileBuilder .New() .SetNamespace(CreateStateNamespace(descriptor.RuntimeType.NamespaceWithoutGlobal)) .AddType(classBuilder) .Build(writer); }
public Where(CodeFileBuilder builder) { _builder = builder; }
public Table(CodeFileBuilder builder) { _builder = builder; }
public UnsavedValue(CodeFileBuilder builder) { _builder = builder; }
protected override void Generate( CodeWriter writer, ITypeDescriptor typeDescriptor, out string fileName, out string?path) { ComplexTypeDescriptor complexTypeDescriptor = typeDescriptor as ComplexTypeDescriptor ?? throw new InvalidOperationException( "A result entity mapper can only be generated for complex types"); var className = CreateResultInfoName(complexTypeDescriptor.RuntimeType.Name); fileName = className; path = State; ClassBuilder classBuilder = ClassBuilder .New() .AddImplements(TypeNames.IOperationResultDataInfo) .SetName(fileName); ConstructorBuilder constructorBuilder = classBuilder .AddConstructor() .SetTypeName(complexTypeDescriptor.RuntimeType.Name); foreach (var prop in complexTypeDescriptor.Properties) { TypeReferenceBuilder propTypeBuilder = prop.Type.ToStateTypeReference(); // Add Property to class classBuilder .AddProperty(prop.Name) .SetComment(prop.Description) .SetType(propTypeBuilder) .SetPublic(); // Add initialization of property to the constructor var paramName = GetParameterName(prop.Name); constructorBuilder.AddParameter(paramName).SetType(propTypeBuilder); constructorBuilder.AddCode( AssignmentBuilder .New() .SetLefthandSide(prop.Name) .SetRighthandSide(paramName)); } classBuilder .AddProperty("EntityIds") .SetType(TypeNames.IReadOnlyCollection.WithGeneric(TypeNames.EntityId)) .AsLambda(_entityIds); classBuilder .AddProperty("Version") .SetType(TypeNames.UInt64) .AsLambda(_version); AddConstructorAssignedField( TypeNames.IReadOnlyCollection.WithGeneric(TypeNames.EntityId), _entityIds, classBuilder, constructorBuilder); AddConstructorAssignedField( TypeNames.UInt64, _version, classBuilder, constructorBuilder, true); // WithVersion const string version = nameof(version); classBuilder .AddMethod("WithVersion") .SetAccessModifier(AccessModifier.Public) .SetReturnType(TypeNames.IOperationResultDataInfo) .AddParameter(version, x => x.SetType(TypeNames.UInt64)) .AddCode(MethodCallBuilder .New() .SetReturn() .SetNew() .SetMethodName(className) .AddArgumentRange( complexTypeDescriptor.Properties.Select(x => x.Name.Value)) .AddArgument(_entityIds) .AddArgument(version)); CodeFileBuilder .New() .SetNamespace(CreateStateNamespace( complexTypeDescriptor.RuntimeType.NamespaceWithoutGlobal)) .AddType(classBuilder) .Build(writer); }
public Cascade(CodeFileBuilder builder) { _builder = builder; }
protected override void Generate( CodeWriter writer, OperationDescriptor descriptor, out string fileName, out string?path) { var documentName = CreateDocumentTypeName(descriptor.RuntimeType.Name); fileName = documentName; path = null; string operationKind = descriptor switch { MutationOperationDescriptor => "Mutation", QueryOperationDescriptor => "Query", SubscriptionOperationDescriptor => "Subscription", _ => throw new ArgumentOutOfRangeException(nameof(descriptor)) }; ClassBuilder classBuilder = ClassBuilder .New() .SetName(fileName) .AddImplements(TypeNames.IDocument) .SetComment( XmlCommentBuilder .New() .SetSummary( string.Format( CodeGenerationResources.OperationServiceDescriptor_Description, descriptor.Name)) .AddCode(descriptor.BodyString)); classBuilder .AddConstructor() .SetPrivate(); classBuilder .AddProperty("Instance") .SetStatic() .SetType(documentName) .SetValue($"new {documentName}()"); classBuilder .AddProperty("Kind") .SetType(TypeNames.OperationKind) .AsLambda($"{TypeNames.OperationKind}.{operationKind}"); if (descriptor.Strategy == RequestStrategy.PersistedQuery) { classBuilder .AddProperty("Body") .SetType(TypeNames.IReadOnlySpan.WithGeneric(TypeNames.Byte)) .AsLambda($"new {TypeNames.Byte}[0]"); } else { classBuilder .AddProperty("Body") .SetType(TypeNames.IReadOnlySpan.WithGeneric(TypeNames.Byte)) .AsLambda(GetByteArray(descriptor.Body)); } classBuilder .AddProperty("Hash") .SetType(TypeNames.DocumentHash) .SetValue( $@"new {TypeNames.DocumentHash}(" + $@"""{descriptor.HashAlgorithm}"", " + $@"""{descriptor.HashValue}"")"); classBuilder .AddMethod("ToString") .SetPublic() .SetOverride() .SetReturnType(TypeNames.String) .AddCode("#if NETSTANDARD2_0") .AddCode(MethodCallBuilder .New() .SetReturn() .SetMethodName(TypeNames.EncodingUtf8, nameof(Encoding.UTF8.GetString)) .AddArgument("Body.ToArray()")) .AddCode("#else") .AddCode(MethodCallBuilder .New() .SetReturn() .SetMethodName(TypeNames.EncodingUtf8, nameof(Encoding.UTF8.GetString)) .AddArgument("Body")) .AddCode("#endif"); CodeFileBuilder .New() .SetNamespace(descriptor.RuntimeType.NamespaceWithoutGlobal) .AddType(classBuilder) .Build(writer); }
protected override void Generate( CodeWriter writer, OperationDescriptor descriptor, out string fileName, out string?path) { fileName = descriptor.RuntimeType.Name; path = null; ClassBuilder classBuilder = ClassBuilder .New() .SetComment( XmlCommentBuilder .New() .SetSummary( string.Format( CodeGenerationResources.OperationServiceDescriptor_Description, descriptor.Name)) .AddCode(descriptor.BodyString)) .AddImplements(descriptor.InterfaceType.ToString()) .SetName(fileName); ConstructorBuilder constructorBuilder = classBuilder .AddConstructor() .SetTypeName(fileName); var runtimeTypeName = descriptor.ResultTypeReference.GetRuntimeType().Name; AddConstructorAssignedField( TypeNames.IOperationExecutor.WithGeneric(runtimeTypeName), _operationExecutor, classBuilder, constructorBuilder); AddInjectedSerializers(descriptor, constructorBuilder, classBuilder); if (descriptor is not SubscriptionOperationDescriptor) { classBuilder.AddMethod(CreateExecuteMethod(descriptor, runtimeTypeName)); } classBuilder.AddMethod(CreateWatchMethod(descriptor, runtimeTypeName)); classBuilder.AddMethod(CreateRequestMethod(descriptor)); classBuilder.AddMethod(CreateRequestVariablesMethod(descriptor)); AddFormatMethods(descriptor, classBuilder); classBuilder .AddProperty("ResultType") .SetType(TypeNames.Type) .AsLambda($"typeof({runtimeTypeName})") .SetInterface(TypeNames.IOperationRequestFactory); MethodCallBuilder createRequestCall = MethodCallBuilder .New() .SetReturn() .SetMethodName(_createRequest); if (descriptor.Arguments.Count > 0) { createRequestCall.AddArgument($"{_variables}!"); } classBuilder .AddMethod("Create") .SetReturnType(TypeNames.OperationRequest) .SetInterface(TypeNames.IOperationRequestFactory) .AddParameter( _variables, x => x.SetType( TypeNames.IReadOnlyDictionary .WithGeneric(TypeNames.String, TypeNames.Object.MakeNullable()) .MakeNullable())) .AddCode(createRequestCall); CodeFileBuilder .New() .SetNamespace(descriptor.RuntimeType.NamespaceWithoutGlobal) .AddType(classBuilder) .Build(writer); }
public void BeforeEachTest() { _builder = new CodeFileBuilder(); _nullability = new Nullability(_builder); }
public Index(CodeFileBuilder builder) { _builder = builder; }