示例#1
0
        public void Visit_WithDesignTimeHost_GeneratesBaseClass_ForModelChunks()
        {
            // Arrange
            var expected =
"MyBase<" + Environment.NewLine +
"#line 1 \"\"" + Environment.NewLine +
"My_Generic.After.Periods" + Environment.NewLine +
Environment.NewLine +
"#line default" + Environment.NewLine +
"#line hidden" + Environment.NewLine +
">";
            var writer = new CSharpCodeWriter();
            var context = CreateContext();
            context.Host.DesignTimeMode = true;

            var visitor = new ModelChunkVisitor(writer, context);
            var factory = SpanFactory.CreateCsHtml();
            var node = (Span)factory.Code("Some code")
                                    .As(new ModelChunkGenerator("MyType", "MyPropertyName"));

            // Act
            visitor.Accept(new Chunk[]
            {
                new LiteralChunk(),
                new ModelChunk("MyBase", "My_Generic.After.Periods") { Association = node }
            });
            var code = writer.GenerateCode();

            // Assert
            Assert.Equal(expected, code);
        }
        public void RenderAttributeValue_RendersModelExpressionsCorrectly(string modelExpressionType,
                                                                          string propertyType,
                                                                          string expectedValue)
        {
            // Arrange
            var renderer = new MvcTagHelperAttributeValueCodeRenderer(
                new GeneratedTagHelperAttributeContext
                {
                    ModelExpressionTypeName = modelExpressionType,
                    CreateModelExpressionMethodName = "SomeMethod"
                });
            var attributeDescriptor = new TagHelperAttributeDescriptor("MyAttribute", "SomeProperty", propertyType);
            var writer = new CSharpCodeWriter();
            var generatorContext = new CodeGeneratorContext(host: null,
                                                            className: string.Empty,
                                                            rootNamespace: string.Empty,
                                                            sourceFile: string.Empty,
                                                            shouldGenerateLinePragmas: true);
            var errorSink = new ParserErrorSink();
            var context = new CodeBuilderContext(generatorContext, errorSink);

            // Act
            renderer.RenderAttributeValue(attributeDescriptor, writer, context,
            (codeWriter) =>
            {
                codeWriter.Write("MyValue");
            },
            complexValue: false);

            // Assert
            Assert.Equal(expectedValue, writer.GenerateCode());
        }
        protected override CSharpCodeWritingScope BuildClassDeclaration(CSharpCodeWriter writer)
        {
            // Grab the last model chunk so it gets intellisense.
            var modelChunk = ChunkHelper.GetModelChunk(Context.CodeTreeBuilder.CodeTree);

            Model = modelChunk != null ? modelChunk.ModelType : _defaultModel;

            // If there were any model chunks then we need to modify the class declaration signature.
            if (modelChunk != null)
            {
                writer.Write(string.Format(CultureInfo.InvariantCulture, "public class {0} : ", Context.ClassName));

                var modelVisitor = new ModelChunkVisitor(writer, Context);
                // This generates the base class signature
                modelVisitor.Accept(modelChunk);

                writer.WriteLine();

                return new CSharpCodeWritingScope(writer);
            }
            else
            {
                return base.BuildClassDeclaration(writer);
            }
        }
示例#4
0
        public void Visit_GeneratesProperties_ForInjectChunks()
        {
            // Arrange
            var expected =
@"[ActivateAttribute]
public MyType1 MyPropertyName1 { get; private set; }
[ActivateAttribute]
public MyType2 @MyPropertyName2 { get; private set; }
";
            var writer = new CSharpCodeWriter();
            var context = CreateContext();

            var visitor = new InjectChunkVisitor(writer, context, "ActivateAttribute");
            var factory = SpanFactory.CreateCsHtml();
            var node = (Span)factory.Code("Some code")
                                    .As(new InjectParameterGenerator("MyType", "MyPropertyName"));

            // Act
            visitor.Accept(new Chunk[]
            {
                new LiteralChunk(),
                new InjectChunk("MyType1", "MyPropertyName1") { Association = node },
                new InjectChunk("MyType2", "@MyPropertyName2") { Association = node }
            });
            var code = writer.GenerateCode();

            // Assert
            Assert.Equal(expected, code);
        }
示例#5
0
        protected override CSharpCodeWritingScope BuildClassDeclaration(CSharpCodeWriter writer)
        {
            // Grab the last model chunk so it gets intellisense.
            // NOTE: If there's more than 1 model chunk there will be a Razor error BUT we want intellisense to 
            // show up on the current model chunk that the user is typing.
            var modelChunk = Context.CodeTreeBuilder.CodeTree.Chunks.OfType<ModelChunk>()
                                                                    .LastOrDefault();

            Model = modelChunk != null ? modelChunk.ModelType : _hostOptions.DefaultModel;

            // If there were any model chunks then we need to modify the class declaration signature.
            if (modelChunk != null)
            {
                writer.Write(string.Format(CultureInfo.InvariantCulture, "public class {0} : ", Context.ClassName));

                var modelVisitor = new ModelChunkVisitor(writer, Context);
                // This generates the base class signature
                modelVisitor.Accept(modelChunk);

                writer.WriteLine();

                return new CSharpCodeWritingScope(writer);
            }
            else
            {
                return base.BuildClassDeclaration(writer);
            }
        }
            protected override CSharpCodeVisitor CreateCSharpCodeVisitor(
                CSharpCodeWriter writer,
                CodeBuilderContext context)
            {
                var bodyVisitor = base.CreateCSharpCodeVisitor(writer, context);

                bodyVisitor.TagHelperRenderer.AttributeValueCodeRenderer = new CustomTagHelperAttributeCodeRenderer();

                return bodyVisitor;
            }
示例#7
0
                protected override CSharpCodeVisitor CreateCSharpCodeVisitor(
                    CSharpCodeWriter writer,
                    CodeGeneratorContext context)
                {
                    var visitor = base.CreateCSharpCodeVisitor(writer, context);

                    visitor.TagHelperRenderer = new NoUniqueIdsTagHelperCodeRenderer(visitor, writer, context)
                    {
                        AttributeValueCodeRenderer =
                            new MvcTagHelperAttributeValueCodeRenderer(_tagHelperAttributeContext)
                    };
                    return(visitor);
                }
示例#8
0
        protected override void BuildConstructor([NotNull] CSharpCodeWriter writer)
        {
            base.BuildConstructor(writer);

            writer.WriteLineHiddenDirective();

            var injectVisitor = new InjectChunkVisitor(writer, Context, _activateAttribute);

            injectVisitor.Accept(Context.CodeTreeBuilder.CodeTree.Chunks);

            writer.WriteLine();
            writer.WriteLineHiddenDirective();
        }
        private static TrackingUniqueIdsTagHelperCodeRenderer CreateCodeRenderer()
        {
            var writer = new CSharpCodeWriter();
            var codeGeneratorContext = CreateContext();
            var visitor      = new CSharpCodeVisitor(writer, codeGeneratorContext);
            var codeRenderer = new TrackingUniqueIdsTagHelperCodeRenderer(
                visitor,
                writer,
                codeGeneratorContext);

            visitor.TagHelperRenderer = codeRenderer;
            return(codeRenderer);
        }
        public StringBuilder GenerateClasses(string jsonInput, out string errorMessage)
        {
            errorMessage = string.Empty;
            try
            {
                JObject[] examples = null;
                try
                {
                    using (var sr = new StringReader(jsonInput))
                        using (var reader = new JsonTextReader(sr))
                        {
                            var json = JToken.ReadFrom(reader);
                            if (json is JArray)
                            {
                                examples = ((JArray)json).Cast <JObject>().ToArray();
                            }
                            else if (json is JObject)
                            {
                                examples = new[] { (JObject)json };
                            }
                        }
                }
                catch (Exception ex)
                {
                    errorMessage = "Wrong JSON format";
                    return(new StringBuilder());
                }

                if (CodeWriter == null)
                {
                    CodeWriter = new CSharpCodeWriter();
                }

                Types = new List <JsonType>();
                Names.Add("Root");
                var rootType = new JsonType(this, examples[0]);
                rootType.IsRoot = true;
                rootType.AssignName("Root");
                GenerateClass(examples, rootType);
                StringBuilder builder = new StringBuilder();
                WriteClassesToFile(builder, Types);

                return(builder);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message + Environment.NewLine + ex.StackTrace;
                return(new StringBuilder());
            }
        }
示例#11
0
        protected override CSharpCodeWritingScope BuildClassDeclaration(CSharpCodeWriter writer)
        {
            if (Context.Host.DesignTimeMode &&
                string.Equals(
                    Path.GetFileName(Context.SourceFile),
                    ViewHierarchyUtility.ViewImportsFileName,
                    StringComparison.OrdinalIgnoreCase))
            {
                // Write a using TModel = System.Object; token during design time to make intellisense work
                writer.WriteLine($"using {ChunkHelper.TModelToken} = {typeof(object).FullName};");
            }

            return(base.BuildClassDeclaration(writer));
        }
示例#12
0
        public void Run()
        {
            string             path = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_2_CHECK_RESERVED_KEYWORDS_INPUT.txt"; string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_2_CHECK_RESERVED_KEYWORDS_OUTPUT.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter = csharpCodeWriter;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
示例#13
0
        public void Run()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_5_BASIC_SCENARIO_INPUT.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_5_BASIC_SCENARIO_OUTPUT.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
示例#14
0
        public void Visit_WithDesignTimeHost_GeneratesPropertiesAndLinePragmas_ForInjectChunks()
        {
            // Arrange
            var expected = string.Join(Environment.NewLine,
                                       @"[Microsoft.AspNet.Mvc.ActivateAttribute]",
                                       @"public",
                                       @"#line 1 """"",
                                       @"MyType1 MyPropertyName1",
                                       "",
                                       @"#line default",
                                       @"#line hidden",
                                       @"{ get; private set; }",
                                       @"[Microsoft.AspNet.Mvc.ActivateAttribute]",
                                       @"public",
                                       @"#line 1 """"",
                                       @"MyType2 @MyPropertyName2",
                                       "",
                                       @"#line default",
                                       @"#line hidden",
                                       @"{ get; private set; }",
                                       "");
            var writer  = new CSharpCodeWriter();
            var context = CreateContext();

            context.Host.DesignTimeMode = true;

            var visitor = new InjectChunkVisitor(writer, context, "Microsoft.AspNet.Mvc.ActivateAttribute");
            var factory = SpanFactory.CreateCsHtml();
            var node    = (Span)factory.Code("Some code")
                          .As(new InjectParameterGenerator("MyType", "MyPropertyName"));

            // Act
            visitor.Accept(new Chunk[]
            {
                new LiteralChunk(),
                new InjectChunk("MyType1", "MyPropertyName1")
                {
                    Association = node
                },
                new InjectChunk("MyType2", "@MyPropertyName2")
                {
                    Association = node
                }
            });
            var code = writer.GenerateCode();

            // Assert
            Assert.Equal(expected, code);
        }
示例#15
0
        public void Run()
        {
            string             path = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_6_SETTINGS_JSONPROPERTYNAME_NETCORE_INPUT.txt"; string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_6_SETTINGS_JSONPROPERTYNAME_NETCORE_OUTPUT.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter          = csharpCodeWriter;
            jsonClassGenerator.UseJsonPropertyName = true;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
示例#16
0
        public MvcCSharpCodeVisitor(
            CSharpCodeWriter writer,
            CodeGeneratorContext context)
            : base(writer, context)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
        }
示例#17
0
    public override void WriteOutputArgument(TrampolineContext context, CSharpCodeWriter writer)
    {
        writer.Write('(');
        context.WriteType(OutputType);
        writer.Write(')');

        if (ByRefKind is not null)
        {
            writer.WriteIdentifier(TemporaryName);
        }
        else
        {
            writer.WriteIdentifier(Name);
        }
    }
        public static CSharpCodeWriter WriteLineNumberDirective(this CSharpCodeWriter writer, MappingLocation location, string file)
        {
            if (location.FilePath != null)
            {
                file = location.FilePath;
            }

            if (writer.Builder.Length >= writer.NewLine.Length && !writer.IsAfterNewLine)
            {
                writer.WriteLine();
            }

            var lineNumberAsString = (location.LineIndex + 1).ToString(CultureInfo.InvariantCulture);

            return(writer.Write("#line ").Write(lineNumberAsString).Write(" \"").Write(file).WriteLine("\""));
        }
        public void Run_2()
        {
            string path1       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_INPUT_1.txt";
            string resultPath1 = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_4_BracketError_OUTPUT_1.txt";
            string input1      = File.ReadAllText(path1);

            CSharpCodeWriter   csharpCodeWriter1   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator1 = new JsonClassGenerator();

            jsonClassGenerator1.CodeWriter = csharpCodeWriter1;

            string returnVal1      = jsonClassGenerator1.GenerateClasses(input1, out string errorMessage1).ToString();
            string resultsCompare1 = File.ReadAllText(resultPath1);

            Assert.AreEqual(resultsCompare1.NormalizeOutput(), returnVal1.NormalizeOutput());
        }
示例#20
0
        protected override void BuildConstructor([NotNull] CSharpCodeWriter writer)
        {
            // TODO: Move this to a proper extension point. Right now, we don't have a place to print out properties
            // in the generated view.
            // Tracked by #773
            base.BuildConstructor(writer);

            writer.WriteLineHiddenDirective();

            var injectVisitor = new InjectChunkVisitor(writer, Context, _activateAttribute);

            injectVisitor.Accept(Context.CodeTreeBuilder.CodeTree.Chunks);

            writer.WriteLine();
            writer.WriteLineHiddenDirective();
        }
示例#21
0
        protected override void BuildConstructor(CSharpCodeWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            writer.WriteLineHiddenDirective();

            var injectVisitor = new InjectChunkVisitor(writer, Context, "Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute");

            injectVisitor.Accept(Context.ChunkTreeBuilder.Root.Children);

            var modelVisitor = new ModelChunkVisitor(writer, Context);

            modelVisitor.Accept(Context.ChunkTreeBuilder.Root.Children);
            if (modelVisitor.ModelType != null)
            {
                writer.WriteLine();

                // public ModelType Model => ViewData?.Model ?? default(ModelType);
                writer.Write("public ").Write(modelVisitor.ModelType).Write(" Model => ViewData?.Model ?? default(").Write(modelVisitor.ModelType).Write(");");
            }

            writer.WriteLine();
            var modelType = modelVisitor.ModelType ?? Context.ClassName;

            // public new ViewDataDictionary<Model> ViewData => (ViewDataDictionary<Model>)base.ViewData;
            var viewDataType = $"global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<{modelType}>";

            writer.Write("public new ").Write(viewDataType).Write($" ViewData => ({viewDataType})base.ViewData;");

            // [RazorInject]
            // public IHtmlHelper<Model> Html { get; private set; }
            writer.WriteLine();
            writer.Write("[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]").WriteLine();
            writer.Write($"public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<{modelType}> Html {{ get; private set; }}").WriteLine();

            // [RazorInject]
            // public ILogger<PageClass> Logger { get; private set; }
            writer.WriteLine();
            writer.Write("[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]").WriteLine();
            writer.Write($"public global::Microsoft.Extensions.Logging.ILogger<{Context.ClassName}> Logger {{ get; private set; }}").WriteLine();

            writer.WriteLine();
            writer.WriteLineHiddenDirective();
        }
        public void Run()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_2_SETTINGS_PASCAL_INPUT.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_2_SETTINGS_PASCAL_OUTPUT.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter    = csharpCodeWriter;
            jsonClassGenerator.UsePascalCase = true;

            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(expected: resultsCompare.NormalizeOutput(), actual: returnVal.NormalizeOutput());
        }
        public void RunSetings()
        {
            string             path               = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_7_DuplictedClasses_INPUT1.txt";
            string             resultPath         = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_7_DuplictedClasses_OUTPUT1.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter        = csharpCodeWriter;
            jsonClassGenerator.UsePascalCase     = true;
            jsonClassGenerator.UseJsonAttributes = true;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
        public void Run()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_3_SETTINGS_FIELDS_INPUT.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_3_SETTINGS_FIELDS_OUTPUT.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter             = csharpCodeWriter;
            jsonClassGenerator.MutableClasses.Members = OutputMembers.AsPublicFields;

            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
        public void Run()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_3_ReplaceSpecialCharacters_INPUT.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_3_ReplaceSpecialCharacters_OUTPUT.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter       = csharpCodeWriter;
            jsonClassGenerator.AttributeLibrary = JsonLibrary.NewtonsoftJson;

            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
示例#26
0
    public override bool WriteBlockBeforeCall(TrampolineContext context, CSharpCodeWriter writer)
    {
        if (ByRefKind is not ByRefKind byRefKind)
        {
            return(false);
        }

        writer.Write("fixed (");
        context.WriteType(TemporaryType);
        writer.Write(' ');
        writer.WriteIdentifier(TemporaryName);
        writer.Write(" = ");
        writer.Write('&');
        writer.WriteIdentifier(Name);
        writer.WriteLine(')');
        return(true);
    }
        public void Run2()
        {
            Assert.Inconclusive(message: "This test is not yet implemented.");
            return;

            string             path               = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_6_DictionaryTest_INPUT2.txt";
            string             resultPath         = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_6_DictionaryTest_OUTPUT2.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter = csharpCodeWriter;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
        public void Run()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_6_SETTINGS_JSONPROPERTYNAME_NETCORE_INPUT.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_6_SETTINGS_JSONPROPERTYNAME_NETCORE_OUTPUT.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter       = csharpCodeWriter;
            jsonClassGenerator.AttributeLibrary = JsonLibrary.SystemTextJson;
            jsonClassGenerator.AttributeUsage   = JsonPropertyAttributeUsage.Always;

            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
示例#29
0
        protected override CSharpCodeVisitor CreateCSharpCodeVisitor(
            CSharpCodeWriter writer,
            CodeGeneratorContext context)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var csharpCodeVisitor = base.CreateCSharpCodeVisitor(writer, context);

            return(csharpCodeVisitor);
        }
示例#30
0
        public LinePragmaWriter(CSharpCodeWriter writer, MappingLocation documentLocation)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            if (documentLocation == null)
            {
                throw new ArgumentNullException(nameof(documentLocation));
            }

            _writer      = writer;
            _startIndent = _writer.CurrentIndent;
            _writer.ResetIndent();
            _writer.WriteLineNumberDirective(documentLocation, documentLocation.FilePath);
            _writer.SetIndent(_startIndent);
        }
示例#31
0
        protected override void BuildConstructor(CSharpCodeWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            base.BuildConstructor(writer);

            writer.WriteLineHiddenDirective();

            var injectVisitor = new InjectChunkVisitor(writer, Context, _injectAttribute);

            injectVisitor.Accept(Context.ChunkTreeBuilder.ChunkTree.Chunks);

            writer.WriteLine();
            writer.WriteLineHiddenDirective();
        }
        public void TestGenerator()
        {
            var         json   = @"{""employees"": [
                        {  ""firstName"":""John"" , ""lastName"":""Doe"" }, 
                        {  ""firstName"":""Anna"" , ""lastName"":""Smith"" }, 
                        { ""firstName"": ""Peter"" ,  ""lastName"": ""Jones "" }
                        ]
                        }".Trim();
            ICodeWriter writer = new CSharpCodeWriter();

            var gen = new JsonClassGenerator();

            gen.Example                 = json;
            gen.InternalVisibility      = false;
            gen.CodeWriter              = writer;
            gen.ExplicitDeserialization = false;

            gen.Namespace = "Demo";


            gen.NoHelperClass      = true;
            gen.SecondaryNamespace = null;
            gen.UseProperties      = true;
            gen.UsePascalCase      = true;
            gen.PropertyAttribute  = "DataMember";

            gen.UseNestedClasses           = false;
            gen.ApplyObfuscationAttributes = false;
            gen.SingleFile = true;
            gen.ExamplesInDocumentation = false;
            gen.TargetFolder            = null;
            gen.SingleFile = true;
            var result = "";

            using (var sw = new StringWriter())
            {
                gen.OutputStream = sw;
                gen.GenerateClasses();
                sw.Flush();

                result = sw.ToString();
            }
            Assert.NotEmpty(result);
        }
示例#33
0
        public void Visit_IgnoresNonModelChunks()
        {
            // Arrange
            var writer = new CSharpCodeWriter();
            var context = CreateContext();

            var visitor = new ModelChunkVisitor(writer, context);

            // Act
            visitor.Accept(new Chunk[]
            {
                new LiteralChunk(),
                new CodeAttributeChunk()
            });
            var code = writer.GenerateCode();

            // Assert
            Assert.Empty(code);
        }
示例#34
0
        public void Run2()
        {
            string path       = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_9_HANDLE_NUMBERS_INPUT1.txt";
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_9_HANDLE_NUMBERS_OUTPUT1.txt";
            string input      = File.ReadAllText(path);

            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter       = csharpCodeWriter;
            jsonClassGenerator.UsePascalCase    = true;
            jsonClassGenerator.AttributeLibrary = JsonLibrary.NewtonsoftJson;
            jsonClassGenerator.AttributeUsage   = JsonPropertyAttributeUsage.Always;

            string returnVal      = jsonClassGenerator.GenerateClasses(input, out string errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.NormalizeOutput(), returnVal.NormalizeOutput());
        }
示例#35
0
        public void Visit_IgnoresNonModelChunks()
        {
            // Arrange
            var writer  = new CSharpCodeWriter();
            var context = CreateContext();

            var visitor = new ModelChunkVisitor(writer, context);

            // Act
            visitor.Accept(new Chunk[]
            {
                new LiteralChunk(),
                new CodeAttributeChunk()
            });
            var code = writer.GenerateCode();

            // Assert
            Assert.Empty(code);
        }
        public void Run()
        {
            string path = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_2_SETTINGS_PASCAL_INPUT.txt"; 
            string resultPath = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_2_SETTINGS_PASCAL_OUTPUT.txt";
            string input = File.ReadAllText(path);

            CSharpCodeWriter csharpCodeWriter = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator
            {
                CodeWriter = csharpCodeWriter,
                UsePascalCase = true
            };

            string errorMessage;
            string returnVal = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);
            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), 
                            returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
        public void Run()
        {
            string             path               = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_SETTINGS_INPUT.txt";
            string             resultPath         = Directory.GetCurrentDirectory().Replace("bin\\Debug", "") + @"Test_1_SETTINGS_OUTPUT.txt";
            string             input              = File.ReadAllText(path);
            string             errorMessage       = string.Empty;
            CSharpCodeWriter   csharpCodeWriter   = new CSharpCodeWriter();
            JsonClassGenerator jsonClassGenerator = new JsonClassGenerator();

            jsonClassGenerator.CodeWriter = csharpCodeWriter;
            Dictionary <string, string> settings = new Dictionary <string, string>();

            jsonClassGenerator.UsePascalCase = true;
            jsonClassGenerator.UseFields     = true;
            string returnVal      = jsonClassGenerator.GenerateClasses(input, out errorMessage).ToString();
            string resultsCompare = File.ReadAllText(resultPath);

            Assert.AreEqual(resultsCompare.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""), returnVal.Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", ""));
        }
 private static TrackingUniqueIdsTagHelperCodeRenderer CreateCodeRenderer()
 {
     var writer = new CSharpCodeWriter();
     var codeBuilderContext = CreateContext();
     var visitor = new CSharpCodeVisitor(writer, codeBuilderContext);
     var codeRenderer = new TrackingUniqueIdsTagHelperCodeRenderer(
         visitor,
         writer,
         codeBuilderContext);
     visitor.TagHelperRenderer = codeRenderer;
     return codeRenderer;
 }
        public void Visit_WithDesignTimeHost_GeneratesPropertiesAndLinePragmas_ForPartialInjectChunks()
        {
            // Arrange
            var expected = @"[Microsoft.AspNet.Mvc.ActivateAttribute]
public
#line 1 """"
MyType1

#line default
#line hidden
{ get; private set; }
";
            var writer = new CSharpCodeWriter();
            var context = CreateContext();
            context.Host.DesignTimeMode = true;

            var visitor = new InjectChunkVisitor(writer, context, "Microsoft.AspNet.Mvc.ActivateAttribute");
            var factory = SpanFactory.CreateCsHtml();
            var node = (Span)factory.Code("Some code")
                                    .As(new InjectParameterGenerator("MyType", "MyPropertyName"));

            // Act
            visitor.Accept(new Chunk[]
            {
                new LiteralChunk(),
                new InjectChunk("MyType1", string.Empty) { Association = node },
            });
            var code = writer.GenerateCode();

            // Assert
            Assert.Equal(expected, code);
        }
        protected override void Establish_context()
        {
            _parsedSpec = new ParsedSpec();
            _parsedSpec.AddScenario(new Scenario
                                    {
                                        Name = "Test_name",
                                        CalledMethods = new[]
                                                            {
                                                                "Given_something",
                                                                "When_I_do_something",
                                                                "Then_something_should_happen"
                                                            }
                                    });
            _parsedSpec.AddHelperMethod("Given_something");
            _parsedSpec.AddHelperMethod("When_I_do_something");
            _parsedSpec.AddHelperMethod("Then_something_should_happen");

            _parsedSpec.AddScenario(new Scenario
                                    {
                                        Name = "Another_test_name",
                                        CalledMethods = new[]
                                                            {
                                                                "Given_something_else",
                                                                "When_I_do_something_else",
                                                                "Then_something_else_should_happen"
                                                            }
                                    });
            _parsedSpec.AddHelperMethod("Given_something");
            _parsedSpec.AddHelperMethod("When_I_do_something");
            _parsedSpec.AddHelperMethod("Then_something_should_happen");
            _parsedSpec.AddHelperMethod("Given_something_else");
            _parsedSpec.AddHelperMethod("When_I_do_something_else");
            _parsedSpec.AddHelperMethod("Then_something_else_should_happen");

            _writer = new CSharpCodeWriter(new MSTestConfiguration());
        }
示例#41
0
 protected override CSharpCodeVisitor CreateCSharpCodeVisitor(CSharpCodeWriter writer, CodeBuilderContext context)
 {
     var visitor = base.CreateCSharpCodeVisitor(writer, context);
     visitor.TagHelperRenderer = new NoUniqueIdsTagHelperCodeRenderer(visitor, writer, context);
     return visitor;
 }
            public override void RenderAttributeValue(
                TagHelperAttributeDescriptor attributeInfo,
                CSharpCodeWriter writer,
                CodeBuilderContext context,
                Action<CSharpCodeWriter> renderAttributeValue,
                bool complexValue)
            {
                writer.Write("**From custom attribute code renderer**: ");

                base.RenderAttributeValue(attributeInfo, writer, context, renderAttributeValue, complexValue);
            }
示例#43
0
        public void Visit_WithDesignTimeHost_GeneratesPropertiesAndLinePragmas_ForInjectChunks()
        {
            // Arrange
            var expected = string.Join(Environment.NewLine,
@"[Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute]",
@"public",
@"#line 1 """"",
@"MyType1 MyPropertyName1",
"",
@"#line default",
@"#line hidden",
@"{ get; private set; }",
@"[Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute]",
@"public",
@"#line 1 """"",
@"MyType2 @MyPropertyName2",
"",
@"#line default",
@"#line hidden",
@"{ get; private set; }",
"");
            var writer = new CSharpCodeWriter();
            var context = CreateContext();
            context.Host.DesignTimeMode = true;

            var visitor = new InjectChunkVisitor(writer, context, "Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute");
            var factory = SpanFactory.CreateCsHtml();
            var node = (Span)factory.Code("Some code")
                                    .As(new InjectParameterGenerator("MyType", "MyPropertyName"));

            // Act
            visitor.Accept(new Chunk[]
            {
                new LiteralChunk(),
                new InjectChunk("MyType1", "MyPropertyName1") { Association = node },
                new InjectChunk("MyType2", "@MyPropertyName2") { Association = node }
            });
            var code = writer.GenerateCode();

            // Assert
            Assert.Equal(expected, code);
        }
            public TrackingUniqueIdsTagHelperCodeRenderer(
                IChunkVisitor bodyVisitor,
                CSharpCodeWriter writer,
                CodeBuilderContext context)
                : base(bodyVisitor, writer, context)
            {

            }