Beispiel #1
0
 public static void Initialize(TestContext context)
 {
     Class1  = SourceGenerator.Generate();
     Class11 = SourceGenerator.Generate(SourceOptions.EmptyElements);
     Class2  = SourceGenerator.Generate(SourceOptions.HasInheritance);
     Class3  = SourceGenerator.Generate(SourceOptions.ImplementsInterfaces);
 }
Beispiel #2
0
        public string RenderSimpleEmptyClass()
        {
            var    sourceInfo = SourceGenerator.Generate(SourceOptions.None);
            string source     = sourceInfo.Key;

            return(GetTranslation(source));
        }
Beispiel #3
0
        public string RenderClassWithMethodStatements()
        {
            var    sourceInfo = SourceGenerator.Generate(SourceOptions.None, ClassOptions.HasContent, FunctionOptions.HasStatements);
            string source     = sourceInfo.Key;

            return(GetTranslation(source));
        }
Beispiel #4
0
        public void Execute()
        {
            if (!string.IsNullOrEmpty(ConnectionString))
            {
                ConfigurationSettings.ConnectionString = ConnectionString;
            }

            Console.WriteLine("Using Database:{0}", NormativeDatabase.Instance.Connection.ConnectionString);
            Console.WriteLine("Base Path:{0}", BasePath);

            switch (MessageTypeToBuild)
            {
            case MessageType.All:
                SourceGenerator.MakeAll(BasePath, Version);
                break;

            case MessageType.EventMapping:
                SourceGenerator.MakeEventMapping(BasePath, Version);
                break;

            case MessageType.Segment:
                SegmentGenerator.MakeAll(BasePath, Version);
                break;

            case MessageType.Message:
                MessageGenerator.MakeAll(BasePath, Version);
                break;

            case MessageType.DataType:
                DataTypeGenerator.MakeAll(BasePath, Version);
                break;
            }
        }
Beispiel #5
0
        public string RenderSimpleClass()
        {
            var    sourceInfo = SourceGenerator.Generate(SourceOptions.None, ClassOptions.HasContent);
            string source     = sourceInfo.Key;

            return(GetTranslation(source));
        }
Beispiel #6
0
        private async Task ExecuteGenerateSourcesCommand()
        {
            IsBusy      = true;
            tokenSource = new CancellationTokenSource();
            token       = tokenSource.Token;

            var sources = new SourceGenerator(Categories);

            ConsoleWrite("Выгрузка листа блоков данных...");

            var resultFile = Path.Combine(RootDirectory, "sources.xlsx");
            await Task.Run(() =>
            {
                ExcelDataWriter.WriteExcelFromArray(resultFile, sources.PrintDBlistToArray(), "DB_list", token);
            }, token).ConfigureAwait(false);

            Progress = 40;
            ConsoleWrite("Старт генерации source-файлов...");
            await sources.SetPeripheryFields(token);

            await sources.PrintAllSourcesToFiles(RootDirectory, token);

            Progress = 90;
            ConsoleWrite("Генерация source-файлов завершена");

            Categories.ReplaceRange(sources.Categories);

            Progress = 0;
            IsBusy   = false;
            ConsoleWrite("Выполнено! Генерация завершена, основная структура сигналов обновлена");
        }
        private void AddRoslynMetadata(string baseTempDirectory, PluginBuilder builder, IPackage package)
        {
            string sourcesDir = CreateSubDirectory(baseTempDirectory, "src");

            this.logger.LogDebug(UIResources.APG_CreatingRoslynSources, sourcesDir);

            SourceGenerator.CreateSourceFiles(typeof(AnalyzerPluginGenerator).Assembly, RoslynResourcesRoot, sourcesDir, new Dictionary <string, string>());

            string[] sourceFiles = Directory.GetFiles(sourcesDir, "*.java", SearchOption.AllDirectories);
            Debug.Assert(sourceFiles.Any(), "Failed to correctly unpack the Roslyn analyzer specific source files");

            foreach (string sourceFile in sourceFiles)
            {
                builder.AddSourceFile(sourceFile);
            }

            builder.SetSourceCodeTokenReplacement(PackageId_Token, package.Id);
            builder.SetSourceCodeTokenReplacement(PackageVersion_Token, package.Version.ToString());
            builder.SetSourceCodeTokenReplacement(AnalyzerId_Token, package.Id);
            builder.SetSourceCodeTokenReplacement(RuleNamespace_Token, package.Id);

            foreach (string extension in Extensions)
            {
                builder.AddExtension(extension);
            }
        }
Beispiel #8
0
        public override void Execute()
        {
            NHapi.Base.NormativeDatabase.Instance.OpenNewConnection(ConnectionString);



            Console.WriteLine("Using Database:{0}", NHapi.Base.NormativeDatabase.Instance.Connection.ConnectionString);
            Console.WriteLine("Base Path:{0}", BasePath);


            switch (MessageTypeToBuild)
            {
            case MessageType.All:
                SourceGenerator.makeAll(BasePath, Version);
                break;

            case MessageType.EventMapping:
                SourceGenerator.MakeEventMapping(BasePath, Version);
                break;

            case MessageType.Segment:
                SegmentGenerator.makeAll(BasePath, Version);
                break;

            case MessageType.Message:
                MessageGenerator.makeAll(BasePath, Version);
                break;
            }
        }
Beispiel #9
0
        public void Indentation()
        {
            AtParser parser = new AtParser();

            parser.Reader = new StringReader(
                @"{
    @code
        int i = 0;
        @text
        123
        @end_text
    @end_code
}");
            parser.Debug = true;

            Intruder parserIntruder = new Intruder(parser);

            parserIntruder.CallMethod <object>("InitParsing");
            parserIntruder.CallMethod <object>("BuildAst");

            SourceGenerator generator = new SourceGenerator();

            generator.Ast       = parserIntruder.ReadField <AtTemplateAst>("ast");
            generator.Debugging = true;
            generator.Walk();

            Console.WriteLine(generator.SourceCode);
        }
Beispiel #10
0
        private void WalkAst()
        {
            SourceGenerator sourceGenerator = new SourceGenerator();

            sourceGenerator.Ast          = this.ast;
            sourceGenerator.Debugging    = this.debug;
            sourceGenerator.TemplateFile = this.templateFile;
            sourceGenerator.Walk();

            this.sourceCode = sourceGenerator.SourceCode;
        }
Beispiel #11
0
        public static GeneratorDriverRunResult RunGenerator(this string source)
        {
            var inputCompilation = CSharpCompilation.Create("compilation",
                                                            new[] { CSharpSyntaxTree.ParseText(source) },
                                                            new[] { MetadataReference.CreateFromFile(typeof(Binder).GetTypeInfo().Assembly.Location) },
                                                            new CSharpCompilationOptions(OutputKind.ConsoleApplication));

            var             generator = new SourceGenerator();
            GeneratorDriver driver    = CSharpGeneratorDriver.Create(generator);

            return(driver.RunGeneratorsAndUpdateCompilation(inputCompilation, out _, out _).GetRunResult());
        }
Beispiel #12
0
        private void BtnExport2TxtClick(object sender, RoutedEventArgs e)
        {
            var mc = dg_Categories.SelectedItem as CategoryModel;
            var cl = new List <CategoryModel>();

            cl.Add(mc);

            var sc    = new SourceGenerator(cl);
            var slist = sc.PrintPeripheryForCategory(mc.Name);

            var outWindow = new TextBufferView(slist);

            outWindow.Show();
        }
        private string BuildTreeFileName(SourceGenerator generator, string key)
        {
            key = key
                  .Replace(":", "_")
                  .Replace(" ", "_")
                  .Replace("\\", "_")
                  .Replace("//", "_")
                  .Replace("<", "_")
                  .Replace(">", "_")
                  .Replace(",", "_")
                  .Replace(":", "_")
                  .Replace(".", "_");

            return(Path.Combine(generator.GetType().Name, key + $".g.cs"));
        }
Beispiel #14
0
        public void SingleStaticText()
        {
            AtTemplateAst ast = new AtTemplateAst();

            ast.Head.Parameters.Add(new Parameter("myName", "string"));
            ast.Body.Directives.Add(new StaticText("Hello World!\r\n", 2));

            SourceGenerator generator = new SourceGenerator();

            generator.Ast       = ast;
            generator.Debugging = true;
            generator.Walk();

            Console.WriteLine(generator.SourceCode);
        }
Beispiel #15
0
        public void makeAll_AllCreated_DefinitionGiven()
        {
            // Arrange
            var baseFolder = GetBaseFolder();
            var version    = GetVersion();

            ConfigurationSettings.XmlFilename = "Mocks\\reverse-nHapi.xml";
            var messageTargetFolder = GetTargetFolder("Message");
            var groupTargetFolder   = GetTargetFolder("Group");

            // Act
            SourceGenerator.makeAll(baseFolder, version);

            // Assert
            // TODO
        }
Beispiel #16
0
        public string RenderSimpleEmptyClass()
        {
            var    sourceInfo = SourceGenerator.Generate(SourceOptions.None);
            string source     = sourceInfo.Key;

            // Getting the AST node
            CSharpSyntaxTree       tree = ASTExtractor.Extract(source);
            SyntaxNode             node = new NodeLocator(tree).LocateLast(typeof(ClassDeclarationSyntax));
            ClassDeclarationSyntax classDeclarationNode = node as ClassDeclarationSyntax;

            // Creating the walker
            var astWalker = ClassASTWalker.Create(classDeclarationNode);

            // Getting the translation unit
            ITranslationUnit translationUnit = astWalker.Walk();

            return(translationUnit.Translate());
        }
Beispiel #17
0
        public void CompileTest()
        {
            var inputCompilation = CSharpCompilation.Create(
                "compilation",
                new[] { CSharpSyntaxTree.ParseText(@"
namespace MyCode
{
    public class Program
    {
        public static void Main(string[] args)
        {
        }
    }
}
") },
                new[]
            {
                MetadataReference.CreateFromFile(typeof(Binder).GetTypeInfo().Assembly.Location),
            },
                new CSharpCompilationOptions(OutputKind.ConsoleApplication));

            var generator = new SourceGenerator();
            var driver    = (GeneratorDriver)CSharpGeneratorDriver.Create(generator);

            driver.RunGeneratorsAndUpdateCompilation(
                inputCompilation,
                out var outputCompilation,
                out var diagnostics);

            diagnostics.Should().BeEmpty();
            outputCompilation.SyntaxTrees.Should().HaveCount(3);

            foreach (var tree in outputCompilation.SyntaxTrees)
            {
                Console.WriteLine($@"
{tree.FilePath}
{tree.GetText()}");
            }

            foreach (var diagnostic in outputCompilation.GetDiagnostics())
            {
                Console.WriteLine($"{diagnostic}");
            }
        }
        public void Add(Generated generated)
        {
            var line = Line;

            line.Add <Generated>();
            if (generated.Argument == null && !generated.IsPartial)
            {
                return;
            }
            SourceGenerator arguments = new SourceGenerator();

            Require(arguments);
            arguments.Line.Add("argument: typeof(").Add(generated.Argument).Add(")");
            if (generated.IsPartial)
            {
                arguments.Add("isPartial: true");
            }
            line.Add($"({string.Join(",", arguments.GetSourceLines())})");
        }
        [TestMethod] // Second test to check the handling of nesting
        public void GenerateSource2()
        {
            // Arrange
            string outputDir = Path.Combine(this.TestContext.TestDeploymentDir, this.TestContext.TestName);
            IDictionary <string, string> replacements = new Dictionary <string, string>();

            replacements.Add("[REPLACE1]", "111");
            replacements.Add("[REPLACE2]", "222");

            // Act
            SourceGenerator.CreateSourceFiles(this.GetType().Assembly, "SonarQube.Plugins.PluginGeneratorTests.resources.myorg.myapp", outputDir, replacements);

            // Assert
            string content;

            content = TestUtils.AssertFileExists("myappClass2.java", outputDir);
            Assert.AreEqual("111zzz", content, "Unexpected file content");

            AssertExpectedSourceFileCount(1, outputDir);
        }
        private void Build(string jarFilePath)
        {
            Assert.IsTrue(File.Exists(jarFilePath), "Jar file does not exist");

            // Get the java source files
            Directory.CreateDirectory(this.tempDir);
            string srcDir = CreateSubDir(this.tempDir, "src");
            string outDir = CreateSubDir(this.tempDir, "out");
            string xxxDir = CreateSubDir(this.tempDir, "xxx");

            SourceGenerator.CreateSourceFiles(this.GetType().Assembly,
                                              "SonarQube.Plugins.IntegrationTests.Roslyn.Resources",
                                              srcDir,
                                              new Dictionary <string, string>());

            JavaCompilationBuilder builder = new JavaCompilationBuilder(this.jdkWrapper);

            foreach (string source in Directory.GetFiles(srcDir, "*.java", SearchOption.AllDirectories))
            {
                builder.AddSources(source);
            }

            // Add the jars required to compile the Java code
            IEnumerable <string> jarFiles = GetCompileDependencies();

            foreach (string jar in jarFiles)
            {
                builder.AddClassPath(jar);
            }

            bool result = builder.Compile(xxxDir, outDir, logger);

            if (!result)
            {
                Assert.Inconclusive("Test setup error: failed to build the Java inspector");
            }

            this.inspectorClassFilePath = GetPluginInspectorClassFilePath(outDir);
        }
Beispiel #21
0
 private async void BtnExportAllClick(object sender, RoutedEventArgs e)
 {
     var sc = new SourceGenerator(Collection.ToList());
     await sc.PrintAllSourcesToFiles(Rootdir, new CancellationToken());
 }
Beispiel #22
0
 static void Main(string[] args)
 {
     SourceGenerator sg = new SourceGenerator()
 }
        public void Execute_Success()
        {
            var compilation = CreateCompilation(@"
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace TestCode
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}");

            var generator = new SourceGenerator();

            var driver = CSharpGeneratorDriver.Create(generator) as GeneratorDriver;

            driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);

            Assert.Empty(diagnostics);
            Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
            var diag = outputCompilation.GetDiagnostics().ToList();

            Assert.Empty(outputCompilation.GetDiagnostics().Where(x => x.Severity != DiagnosticSeverity.Hidden));

            var result = driver.GetRunResult();

            var tree = Assert.Single(result.GeneratedTrees);

            Assert.Empty(result.Diagnostics);

            Assert.Equal(@"namespace Microsoft.AspNetCore.Mvc
{
    public static class UrlHelperExtensions
    {
        public static UrlActions Actions(this IUrlHelper urlHelper)
            => new UrlActions(urlHelper);

        public class UrlActions
        {
            private readonly IUrlHelper urlHelper;
            public UrlActions(IUrlHelper urlHelper)
            {
                this.urlHelper = urlHelper;
            }

            public HomeControllerActions Home
                => new HomeControllerActions(urlHelper);

            public class HomeControllerActions
            {
                private readonly IUrlHelper urlHelper;
                public HomeControllerActions(IUrlHelper urlHelper)
                {
                    this.urlHelper = urlHelper;
                }

                public string Index()
                    => urlHelper.Action(""Index"", ""Home"", new { area = """" });
            }
        }

    }
}
", tree.ToString());
        }
Beispiel #24
0
        public void Execute_Pages_Success()
        {
            var compilation = CreateCompilation(@"
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace AspNetCoreSamplePages.Pages.Feature
{
    public class Page : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public string GetProperty { get; set; }

        [BindProperty(SupportsGet = true, Name = ""NamedGetProperty"")]
        public string GetProperty2 { get; set; }

        [BindProperty]
        public string PostProperty { get; set; }

        [FromQuery]
        public string QueryParameter { get; set; }

        [FromQuery(Name = ""NamedQueryParameter"")]
        public string QueryParameter2 { get; set; }

        public void OnGet(int page, int pageSize)
        {
        }

        public async Task OnPostAsync(string str)
        {
            await Task.Delay(1);
        }

        public async Task OnGetHandlerAsync()
        {
            await Task.Delay(1);
        }
    }
}");

            var generator = new SourceGenerator();

            var driver = CSharpGeneratorDriver.Create(generator) as GeneratorDriver;

            driver = driver.AddAdditionalTexts(ImmutableArray.Create <AdditionalText>(new InMemoryAdditionalText("/AspNetCoreSamplePages/Pages/Feature/Page.cshtml", @"@page ""{id:int}""
@model AspNetCoreSamplePages.Pages.Feature.Page

<h1>Hello, World!</h1>
")));

            driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);

            diagnostics.Should().BeEmpty();
            outputCompilation.SyntaxTrees.Should().HaveCount(3);

            var nonHiddenDiagnostics = outputCompilation.GetDiagnostics().Where(x => x.Severity != DiagnosticSeverity.Hidden);

            nonHiddenDiagnostics.Should().BeEmpty();

            var result = driver.GetRunResult();

            result.GeneratedTrees.Should().HaveCount(2);
            result.Diagnostics.Should().BeEmpty();

            Assert.Equal(@"// <auto-generated />
namespace Microsoft.AspNetCore.Mvc
{
    public static partial class UrlActionGenerator_UrlHelperExtensions
    {
    }
}
", result.GeneratedTrees[0].ToString(), false, true);

            Assert.Equal(@"// <auto-generated />
namespace Microsoft.AspNetCore.Mvc
{
    public static partial class UrlActionGenerator_UrlHelperExtensions
    {
        public static UrlPages Pages(this IUrlHelper urlHelper)
            => new UrlPages(urlHelper);

        public class UrlPages
        {
            private readonly IUrlHelper urlHelper;
            public UrlPages(IUrlHelper urlHelper)
            {
                this.urlHelper = urlHelper;
            }

            public FeaturePagesFolder Feature
                => new FeaturePagesFolder(urlHelper);

            public class FeaturePagesFolder
            {
                private readonly IUrlHelper urlHelper;
                public FeaturePagesFolder(IUrlHelper urlHelper)
                {
                    this.urlHelper = urlHelper;
                }

                public string Page(int @id, int @page, int @pageSize, string @getProperty = default, string @namedGetProperty = default, string @queryParameter = default, string @namedQueryParameter = default)
                {
                    var __routeValues = Microsoft.AspNetCore.Routing.RouteValueDictionary.FromArray(new System.Collections.Generic.KeyValuePair<string, object>[] {
                        new System.Collections.Generic.KeyValuePair<string, object>(""area"", """"),
                        new System.Collections.Generic.KeyValuePair<string, object>(""handler"", """"),
                        new System.Collections.Generic.KeyValuePair<string, object>(""id"", @id),
                        new System.Collections.Generic.KeyValuePair<string, object>(""page"", @page),
                        new System.Collections.Generic.KeyValuePair<string, object>(""pageSize"", @pageSize),
                        new System.Collections.Generic.KeyValuePair<string, object>(""getProperty"", @getProperty),
                        new System.Collections.Generic.KeyValuePair<string, object>(""namedGetProperty"", @namedGetProperty),
                        new System.Collections.Generic.KeyValuePair<string, object>(""queryParameter"", @queryParameter),
                        new System.Collections.Generic.KeyValuePair<string, object>(""namedQueryParameter"", @namedQueryParameter),
                    });
                    return urlHelper.Page(""/Feature/Page"", __routeValues);
                }

                public string Page(int @id, string @str, string @getProperty = default, string @namedGetProperty = default, string @queryParameter = default, string @namedQueryParameter = default)
                {
                    var __routeValues = Microsoft.AspNetCore.Routing.RouteValueDictionary.FromArray(new System.Collections.Generic.KeyValuePair<string, object>[] {
                        new System.Collections.Generic.KeyValuePair<string, object>(""area"", """"),
                        new System.Collections.Generic.KeyValuePair<string, object>(""handler"", """"),
                        new System.Collections.Generic.KeyValuePair<string, object>(""id"", @id),
                        new System.Collections.Generic.KeyValuePair<string, object>(""str"", @str),
                        new System.Collections.Generic.KeyValuePair<string, object>(""getProperty"", @getProperty),
                        new System.Collections.Generic.KeyValuePair<string, object>(""namedGetProperty"", @namedGetProperty),
                        new System.Collections.Generic.KeyValuePair<string, object>(""queryParameter"", @queryParameter),
                        new System.Collections.Generic.KeyValuePair<string, object>(""namedQueryParameter"", @namedQueryParameter),
                    });
                    return urlHelper.Page(""/Feature/Page"", __routeValues);
                }

                public PagePageHandlers PageHandlers
                    => new PagePageHandlers(urlHelper);

                public class PagePageHandlers
                {
                    private readonly IUrlHelper urlHelper;
                    public PagePageHandlers(IUrlHelper urlHelper)
                    {
                        this.urlHelper = urlHelper;
                    }

                    public string Handler(int @id, string @getProperty = default, string @namedGetProperty = default, string @queryParameter = default, string @namedQueryParameter = default)
                    {
                        var __routeValues = Microsoft.AspNetCore.Routing.RouteValueDictionary.FromArray(new System.Collections.Generic.KeyValuePair<string, object>[] {
                            new System.Collections.Generic.KeyValuePair<string, object>(""area"", """"),
                            new System.Collections.Generic.KeyValuePair<string, object>(""handler"", ""Handler""),
                            new System.Collections.Generic.KeyValuePair<string, object>(""id"", @id),
                            new System.Collections.Generic.KeyValuePair<string, object>(""getProperty"", @getProperty),
                            new System.Collections.Generic.KeyValuePair<string, object>(""namedGetProperty"", @namedGetProperty),
                            new System.Collections.Generic.KeyValuePair<string, object>(""queryParameter"", @queryParameter),
                            new System.Collections.Generic.KeyValuePair<string, object>(""namedQueryParameter"", @namedQueryParameter),
                        });
                        return urlHelper.Page(""/Feature/Page"", __routeValues);
                    }

                }

            }

        }

    }
}
", result.GeneratedTrees[1].ToString(), false, true);
        }
Beispiel #25
0
        public void Execute_MVC_Success()
        {
            var compilation = CreateCompilation(@"
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace TestCode
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}");

            var generator = new SourceGenerator();

            var driver = CSharpGeneratorDriver.Create(generator) as GeneratorDriver;

            driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);

            diagnostics.Should().BeEmpty();
            outputCompilation.SyntaxTrees.Should().HaveCount(3);

            var nonHiddenDiagnostics = outputCompilation.GetDiagnostics().Where(x => x.Severity != DiagnosticSeverity.Hidden);

            nonHiddenDiagnostics.Should().BeEmpty();

            var result = driver.GetRunResult();

            result.GeneratedTrees.Should().HaveCount(2);
            result.Diagnostics.Should().BeEmpty();

            Assert.Equal(@"// <auto-generated />
namespace Microsoft.AspNetCore.Mvc
{
    public static partial class UrlActionGenerator_UrlHelperExtensions
    {
        public static UrlActions Actions(this IUrlHelper urlHelper)
            => new UrlActions(urlHelper);

        public class UrlActions
        {
            private readonly IUrlHelper urlHelper;
            public UrlActions(IUrlHelper urlHelper)
            {
                this.urlHelper = urlHelper;
            }

            public HomeControllerActions Home
                => new HomeControllerActions(urlHelper);

            public class HomeControllerActions
            {
                private readonly IUrlHelper urlHelper;
                public HomeControllerActions(IUrlHelper urlHelper)
                {
                    this.urlHelper = urlHelper;
                }

                public string Index()
                {
                    var __routeValues = Microsoft.AspNetCore.Routing.RouteValueDictionary.FromArray(new System.Collections.Generic.KeyValuePair<string, object>[] {
                        new System.Collections.Generic.KeyValuePair<string, object>(""area"", """"),
                    });
                    return urlHelper.Action(""Index"", ""Home"", __routeValues);
                }

            }

        }

    }
}
", result.GeneratedTrees[0].ToString(), false, true);

            Assert.Equal(@"// <auto-generated />
namespace Microsoft.AspNetCore.Mvc
{
    public static partial class UrlActionGenerator_UrlHelperExtensions
    {
    }
}
", result.GeneratedTrees[1].ToString(), false, true);
        }
Beispiel #26
0
        public void Execute_RazorViewsAssembly_DoesNothing()
        {
            var compilation = CreateCompilation(@"
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

[assembly: global::Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute(""Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFactory, Microsoft.AspNetCore.Mvc.Razor"")]

namespace AspNetCoreSamplePages.Pages.Feature
{
    public class Page : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public string GetProperty { get; set; }

        [BindProperty(SupportsGet = true, Name = ""NamedGetProperty"")]
        public string GetProperty2 { get; set; }

        [BindProperty]
        public string PostProperty { get; set; }

        [FromQuery]
        public string QueryParameter { get; set; }

        [FromQuery(Name = ""NamedQueryParameter"")]
        public string QueryParameter2 { get; set; }

        public void OnGet(int page, int pageSize)
        {
        }

        public async Task OnPostAsync(string str)
        {
            await Task.Delay(1);
        }

        public async Task OnGetHandlerAsync()
        {
            await Task.Delay(1);
        }
    }
}
", "AspNetCoreSamplePages.Views");

            var generator = new SourceGenerator();

            var driver = CSharpGeneratorDriver.Create(generator) as GeneratorDriver;

            driver = driver.AddAdditionalTexts(ImmutableArray.Create <AdditionalText>(new InMemoryAdditionalText("/AspNetCoreSamplePages/Pages/Feature/Page.cshtml", @"@page ""{id:int}""
@model AspNetCoreSamplePages.Pages.Feature.Page

<h1>Hello, World!</h1>
")));

            driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);

            diagnostics.Should().BeEmpty();
            outputCompilation.SyntaxTrees.Should().HaveCount(1);

            var hiddenDiagnostics = outputCompilation.GetDiagnostics().Where(x => x.Severity != DiagnosticSeverity.Hidden);

            hiddenDiagnostics.Should().BeEmpty();

            var result = driver.GetRunResult();

            result.GeneratedTrees.Should().BeEmpty();
            result.Diagnostics.Should().BeEmpty();
        }
Beispiel #27
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private string GenerateGeometry(IOMesh mesh)
        {
            // convert mesh to triangles to simplify
            mesh.MakeTriangles();

            // create a unique geometry id
            var geomID = GetUniqueID(mesh.Name + "-geometry");

            // create geometry element
            Geometry geom = new Geometry()
            {
                ID   = geomID,
                Name = mesh.Name
            };

            geom.Mesh = new Mesh();

            // generate sources
            SourceGenerator srcgen = new SourceGenerator();

            srcgen.AddSourceData(
                geomID, Input_Semantic.POSITION,
                mesh.Vertices.SelectMany(e => new float[] { e.Position.X, e.Position.Y, e.Position.Z }).ToArray());

            srcgen.AddSourceData(
                geomID, Input_Semantic.NORMAL,
                mesh.Vertices.SelectMany(e => new float[] { e.Normal.X, e.Normal.Y, e.Normal.Z }).ToArray());

            for (int i = 0; i < 7; i++)
            {
                if (mesh.HasUVSet(i))
                {
                    srcgen.AddSourceData(
                        geomID, Input_Semantic.TEXCOORD,
                        mesh.Vertices.SelectMany(e => new float[] { e.UVs[i].X, e.UVs[i].Y }).ToArray(),
                        i);
                }
            }

            for (int i = 0; i < 7; i++)
            {
                if (mesh.HasColorSet(i))
                {
                    srcgen.AddSourceData(
                        geomID, Input_Semantic.COLOR,
                        mesh.Vertices.SelectMany(e => new float[] { e.Colors[i].X, e.Colors[i].Y, e.Colors[i].Z, e.Colors[i].W }).ToArray(),
                        i);
                }
            }

            // fill in vertex info
            geom.Mesh.Vertices = new Vertices()
            {
                ID    = GetUniqueID(mesh.Name + "-vertices"),
                Input = new Input_Unshared[] {
                    new Input_Unshared()
                    {
                        Semantic = IONET.Collada.Enums.Input_Semantic.POSITION,
                        source   = "#" + srcgen.GetID(Input_Semantic.POSITION)
                    }
                }
            };

            // fill in triangles

            var polyIndex = 0;

            geom.Mesh.Triangles = new Triangles[mesh.Polygons.Count];
            foreach (var poly in mesh.Polygons)
            {
                if (poly.PrimitiveType != IOPrimitive.TRIANGLE)
                {
                    System.Diagnostics.Debug.WriteLine("Warning: " + poly.PrimitiveType + " not currently supported");
                    continue;
                }

                Triangles tri = new Triangles()
                {
                    Count    = poly.Indicies.Count / 3,
                    Material = poly.MaterialName
                };

                List <Input_Shared> inputs = new List <Input_Shared>();
                inputs.Add(new Input_Shared()
                {
                    Semantic = Input_Semantic.VERTEX,
                    Offset   = inputs.Count,
                    source   = "#" + geom.Mesh.Vertices.ID
                });

                inputs.Add(new Input_Shared()
                {
                    Semantic = Input_Semantic.NORMAL,
                    Offset   = inputs.Count,
                    source   = "#" + srcgen.GetID(Input_Semantic.NORMAL)
                });

                for (int i = 0; i < 7; i++)
                {
                    if (mesh.HasUVSet(i))
                    {
                        inputs.Add(new Input_Shared()
                        {
                            Semantic = Input_Semantic.TEXCOORD,
                            source   = "#" + srcgen.GetID(Input_Semantic.TEXCOORD, i),
                            Offset   = inputs.Count,
                            Set      = i
                        });
                    }
                }

                for (int i = 0; i < 7; i++)
                {
                    if (mesh.HasColorSet(i))
                    {
                        inputs.Add(new Input_Shared()
                        {
                            Semantic = Input_Semantic.COLOR,
                            source   = "#" + srcgen.GetID(Input_Semantic.COLOR, i),
                            Offset   = inputs.Count,
                            Set      = i
                        });
                    }
                }

                tri.Input = inputs.ToArray();

                tri.P = new IONET.Collada.Types.Int_Array_String()
                {
                    Value_As_String = string.Join(" ", srcgen.Remap(poly.Indicies))
                };

                geom.Mesh.Triangles[polyIndex++] = tri;
            }


            // generate sources
            geom.Mesh.Source = srcgen.GetSources();


            // add geometry element to document
            if (_collada.Library_Geometries == null)
            {
                _collada.Library_Geometries = new Library_Geometries();
            }

            if (_collada.Library_Geometries.Geometry == null)
            {
                _collada.Library_Geometries.Geometry = new Geometry[0];
            }

            Array.Resize(ref _collada.Library_Geometries.Geometry, _collada.Library_Geometries.Geometry.Length + 1);

            _collada.Library_Geometries.Geometry[_collada.Library_Geometries.Geometry.Length - 1] = geom;

            // return geometry id
            return(geomID);
        }