private void AddBoundAttributes(INamedTypeSymbol type, TagHelperDescriptorBuilder builder)
        {
            var accessibleProperties = GetAccessibleProperties(type);

            foreach (var property in accessibleProperties)
            {
                if (ShouldSkipDescriptorCreation(property))
                {
                    continue;
                }

                builder.BindAttribute(attributeBuilder =>
                {
                    ConfigureBoundAttribute(attributeBuilder, property, type);
                });
            }
        }
Exemplo n.º 2
0
        public void GetLanguageKind_TagHelperElementOwnsName()
        {
            // Arrange
            var descriptor = TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly");

            descriptor.TagMatchingRule(rule => rule.TagName = "test");
            descriptor.SetTypeName("TestTagHelper");
            var text = $"@addTagHelper *, TestAssembly{Environment.NewLine}<test>@Name</test>";

            var(classifiedSpans, tagHelperSpans) = GetClassifiedSpans(text, new[] { descriptor.Build() });

            // Act
            var languageKind = RazorLanguageEndpoint.GetLanguageKind(classifiedSpans, tagHelperSpans, 32 + Environment.NewLine.Length);

            // Assert
            Assert.Equal(RazorLanguageKind.Html, languageKind);
        }
Exemplo n.º 3
0
        public void ViewComponentTagHelperPass_Execute_CreatesViewComponentTagHelper()
        {
            // Arrange
            var codeDocument = CreateDocument(@"
@addTagHelper TestTagHelper, TestAssembly
<tagcloud foo=""17"">");

            var tagHelpers = new[]
            {
                TagHelperDescriptorBuilder.Create(ViewComponentTagHelperConventions.Kind, "TestTagHelper", "TestAssembly")
                .TypeName("__Generated__TagCloudViewComponentTagHelper")
                .BoundAttributeDescriptor(attribute => attribute
                                          .Name("Foo")
                                          .TypeName("System.Int32")
                                          .PropertyName("Foo"))
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("tagcloud"))
                .AddMetadata(ViewComponentTagHelperMetadata.Name, "TagCloud")
                .Build()
            };

            var engine = CreateEngine(tagHelpers);
            var pass   = new ViewComponentTagHelperPass()
            {
                Engine = engine,
            };

            var irDocument = CreateIRDocument(engine, codeDocument);

            var vcthFullName = "AspNetCore.test.__Generated__TagCloudViewComponentTagHelper";

            // Act
            pass.Execute(codeDocument, irDocument);

            // Assert
            var tagHelper = FindTagHelperNode(irDocument);

            Assert.Equal(vcthFullName, Assert.IsType <DefaultTagHelperCreateIntermediateNode>(tagHelper.Children[1]).TypeName);
            Assert.Equal("Foo", Assert.IsType <DefaultTagHelperPropertyIntermediateNode>(tagHelper.Children[2]).PropertyName);


            var @class = FindClassNode(irDocument);

            Assert.Equal(4, @class.Children.Count);

            Assert.IsType <ViewComponentTagHelperIntermediateNode>(@class.Children.Last());
        }
Exemplo n.º 4
0
        public void CreateDescriptor_UnderstandsVariousParameterTypes()
        {
            // Arrange
            var testCompilation = TestCompilation.Create(_assembly);
            var viewComponent   = testCompilation.GetTypeByMetadataName(typeof(VariousParameterViewComponent).FullName);
            var factory         = new ViewComponentTagHelperDescriptorFactory(testCompilation);

            var expectedDescriptor = TagHelperDescriptorBuilder.Create(
                ViewComponentTagHelperConventions.Kind,
                "__Generated__VariousParameterViewComponentTagHelper",
                typeof(VariousParameterViewComponent).GetTypeInfo().Assembly.GetName().Name)
                                     .TypeName("__Generated__VariousParameterViewComponentTagHelper")
                                     .DisplayName("VariousParameterViewComponentTagHelper")
                                     .TagMatchingRuleDescriptor(rule =>
                                                                rule
                                                                .RequireTagName("vc:various-parameter")
                                                                .RequireAttributeDescriptor(attribute => attribute.Name("test-enum"))
                                                                .RequireAttributeDescriptor(attribute => attribute.Name("test-string")))
                                     .BoundAttributeDescriptor(attribute =>
                                                               attribute
                                                               .Name("test-enum")
                                                               .PropertyName("testEnum")
                                                               .TypeName(typeof(VariousParameterViewComponent).FullName + "." + nameof(VariousParameterViewComponent.TestEnum))
                                                               .AsEnum()
                                                               .DisplayName(typeof(VariousParameterViewComponent).FullName + "." + nameof(VariousParameterViewComponent.TestEnum) + " VariousParameterViewComponentTagHelper.testEnum"))
                                     .BoundAttributeDescriptor(attribute =>
                                                               attribute
                                                               .Name("test-string")
                                                               .PropertyName("testString")
                                                               .TypeName(typeof(string).FullName)
                                                               .DisplayName("string VariousParameterViewComponentTagHelper.testString"))
                                     .BoundAttributeDescriptor(attribute =>
                                                               attribute
                                                               .Name("baz")
                                                               .PropertyName("baz")
                                                               .TypeName(typeof(int).FullName)
                                                               .DisplayName("int VariousParameterViewComponentTagHelper.baz"))
                                     .AddMetadata(ViewComponentTagHelperMetadata.Name, "VariousParameter")
                                     .Build();

            // Act
            var descriptor = factory.CreateDescriptor(viewComponent);

            // Assert
            Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
        }
Exemplo n.º 5
0
        public ProjectStateTest()
        {
            TagHelperResolver = new TestTagHelperResolver();

            HostServices = TestServices.Create(
                new IWorkspaceService[]
            {
                new TestProjectSnapshotProjectEngineFactory(),
            },
                new ILanguageService[]
            {
                TagHelperResolver,
            });

            HostProject = new HostProject("c:\\MyProject\\Test.csproj", FallbackRazorConfiguration.MVC_2_0);
            HostProjectWithConfigurationChange = new HostProject("c:\\MyProject\\Test.csproj", FallbackRazorConfiguration.MVC_1_0);

            Workspace = TestWorkspace.Create(HostServices);

            var projectId = ProjectId.CreateNewId("Test");
            var solution  = Workspace.CurrentSolution.AddProject(ProjectInfo.Create(
                                                                     projectId,
                                                                     VersionStamp.Default,
                                                                     "Test",
                                                                     "Test",
                                                                     LanguageNames.CSharp,
                                                                     "c:\\MyProject\\Test.csproj"));

            WorkspaceProject = solution.GetProject(projectId);

            SomeTagHelpers = new List <TagHelperDescriptor>();
            SomeTagHelpers.Add(TagHelperDescriptorBuilder.Create("Test1", "TestAssembly").Build());

            Documents = new HostDocument[]
            {
                new HostDocument("c:\\MyProject\\File.cshtml", "File.cshtml"),
                new HostDocument("c:\\MyProject\\Index.cshtml", "Index.cshtml"),

                // linked file
                new HostDocument("c:\\SomeOtherProject\\Index.cshtml", "Pages\\Index.cshtml"),
            };

            Text       = SourceText.From("Hello, world!");
            TextLoader = () => Task.FromResult(TextAndVersion.Create(Text, VersionStamp.Create()));
        }
Exemplo n.º 6
0
    public void ModelExpressionPass_ModelExpressionProperty_SimpleExpression()
    {
        // Arrange

        // Using \r\n here because we verify line mappings
        var codeDocument = CreateDocument(
            "@addTagHelper TestTagHelper, TestAssembly\r\n<p foo=\"Bar\">");

        var tagHelpers = new[]
        {
            TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly")
            .BoundAttributeDescriptor(attribute =>
                                      attribute
                                      .Name("Foo")
                                      .TypeName("Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression"))
            .TagMatchingRuleDescriptor(rule =>
                                       rule.RequireTagName("p"))
            .Build()
        };

        var engine = CreateEngine(tagHelpers);
        var pass   = new ModelExpressionPass()
        {
            Engine = engine,
        };

        var irDocument = CreateIRDocument(engine, codeDocument);

        // Act
        pass.Execute(codeDocument, irDocument);

        // Assert
        var tagHelper   = FindTagHelperNode(irDocument);
        var setProperty = tagHelper.Children.OfType <TagHelperPropertyIntermediateNode>().Single();

        var expression = Assert.IsType <CSharpExpressionIntermediateNode>(Assert.Single(setProperty.Children));

        Assert.Equal("ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Bar)", GetCSharpContent(expression));

        var originalNode = Assert.IsAssignableFrom <IntermediateToken>(expression.Children[2]);

        Assert.Equal(TokenKind.CSharp, originalNode.Kind);
        Assert.Equal("Bar", originalNode.Content);
        Assert.Equal(new SourceSpan("test.cshtml", 51, 1, 8, 3), originalNode.Source.Value);
    }
        public void GetTagHelperBinding_DoesNotAllowOptOutCharacterPrefix()
        {
            // Arrange
            var documentDescriptors = new[]
            {
                TagHelperDescriptorBuilder.Create("TestType", "TestAssembly")
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("*"))
                .Build()
            };
            var documentContext = TagHelperDocumentContext.Create(string.Empty, documentDescriptors);
            var service         = new DefaultTagHelperFactsService();

            // Act
            var binding = service.GetTagHelperBinding(documentContext, "!a", Enumerable.Empty <KeyValuePair <string, string> >(), parentTag: null, parentIsTagHelper: false);

            // Assert
            Assert.Null(binding);
        }
Exemplo n.º 8
0
        private void CreateContextParameter(TagHelperDescriptorBuilder builder, string childContentName)
        {
            builder.BindAttribute(b =>
            {
                b.Name     = ComponentMetadata.ChildContent.ParameterAttributeName;
                b.TypeName = typeof(string).FullName;
                b.Metadata.Add(ComponentMetadata.Component.ChildContentParameterNameKey, bool.TrueString);

                if (childContentName == null)
                {
                    b.Documentation = ComponentResources.ChildContentParameterName_TopLevelDocumentation;
                }
                else
                {
                    b.Documentation = string.Format(ComponentResources.ChildContentParameterName_Documentation, childContentName);
                }
            });
        }
Exemplo n.º 9
0
        public void GetTagHelpersGivenParent_AllowsRootParentTag()
        {
            // Arrange
            var documentDescriptors = new[]
            {
                TagHelperDescriptorBuilder.Create("TestType", "TestAssembly")
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("div"))
                .Build()
            };
            var documentContext = TagHelperDocumentContext.Create(string.Empty, documentDescriptors);
            var service         = new DefaultTagHelperFactsServiceInternal();

            // Act
            var descriptors = service.GetTagHelpersGivenParent(documentContext, parentTag: null /* root */);

            // Assert
            Assert.Equal(documentDescriptors, descriptors, TagHelperDescriptorComparer.CaseSensitive);
        }
        public void GetTagHelpersGivenParent_AllowsUnspecifiedParentTagHelpers()
        {
            // Arrange
            var documentDescriptors = new[]
            {
                TagHelperDescriptorBuilder.Create("TestType", "TestAssembly")
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("div"))
                .Build()
            };
            var documentContext = TagHelperDocumentContext.Create(string.Empty, documentDescriptors);
            var service         = new DefaultTagHelperFactsService();

            // Act
            var descriptors = service.GetTagHelpersGivenParent(documentContext, "p");

            // Assert
            Assert.Equal(documentDescriptors, descriptors, TagHelperDescriptorComparer.Default);
        }
Exemplo n.º 11
0
        public void GetTagHelpersGivenTag_RequiresTagName()
        {
            // Arrange
            var documentDescriptors = new[]
            {
                TagHelperDescriptorBuilder.Create("TestType", "TestAssembly")
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("strong"))
                .Build()
            };
            var documentContext = TagHelperDocumentContext.Create(string.Empty, documentDescriptors);
            var service         = new DefaultTagHelperFactsService();

            // Act
            var descriptors = service.GetTagHelpersGivenTag(documentContext, "strong", "p");

            // Assert
            Assert.Equal(documentDescriptors, descriptors, TagHelperDescriptorComparer.CaseSensitive);
        }
        public void GetTagHelpersGivenTag_DoesNotAllowOptOutCharacterPrefix()
        {
            // Arrange
            var documentDescriptors = new[]
            {
                TagHelperDescriptorBuilder.Create("TestType", "TestAssembly")
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("*"))
                .Build()
            };
            var documentContext = TagHelperDocumentContext.Create(string.Empty, documentDescriptors);
            var service         = new DefaultTagHelperFactsService();

            // Act
            var descriptors = service.GetTagHelpersGivenTag(documentContext, "!strong", parentTag: null);

            // Assert
            Assert.Empty(descriptors);
        }
        private static RazorCodeActionContext CreateRazorCodeActionContext(
            CodeActionParams request,
            SourceLocation location,
            string filePath,
            string text,
            SourceSpan componentSourceSpan,
            bool supportsFileCreation      = true,
            bool supportsCodeActionResolve = true)
        {
            var shortComponent = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, "Fully.Qualified.Component", "TestAssembly");

            shortComponent.TagMatchingRule(rule => rule.TagName = "Component");
            var fullyQualifiedComponent = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, "Fully.Qualified.Component", "TestAssembly");

            fullyQualifiedComponent.TagMatchingRule(rule => rule.TagName = "Fully.Qualified.Component");

            var tagHelpers = new[] { shortComponent.Build(), fullyQualifiedComponent.Build() };

            var sourceDocument = TestRazorSourceDocument.Create(text, filePath: filePath, relativePath: filePath);
            var projectEngine  = RazorProjectEngine.Create(builder =>
            {
                builder.AddTagHelpers(tagHelpers);
                builder.AddDirective(InjectDirective.Directive);
            });
            var codeDocument = projectEngine.ProcessDesignTime(sourceDocument, FileKinds.Component, Array.Empty <RazorSourceDocument>(), tagHelpers);

            var cSharpDocument               = codeDocument.GetCSharpDocument();
            var diagnosticDescriptor         = new RazorDiagnosticDescriptor("RZ10012", () => "", RazorDiagnosticSeverity.Error);
            var diagnostic                   = RazorDiagnostic.Create(diagnosticDescriptor, componentSourceSpan);
            var cSharpDocumentWithDiagnostic = RazorCSharpDocument.Create(cSharpDocument.GeneratedCode, cSharpDocument.Options, new[] { diagnostic });

            codeDocument.SetCSharpDocument(cSharpDocumentWithDiagnostic);

            var documentSnapshot = Mock.Of <DocumentSnapshot>(document =>
                                                              document.GetGeneratedOutputAsync() == Task.FromResult(codeDocument) &&
                                                              document.GetTextAsync() == Task.FromResult(codeDocument.GetSourceText()) &&
                                                              document.Project.TagHelpers == tagHelpers, MockBehavior.Strict);

            var sourceText = SourceText.From(text);

            var context = new RazorCodeActionContext(request, documentSnapshot, codeDocument, location, sourceText, supportsFileCreation, supportsCodeActionResolve: supportsCodeActionResolve);

            return(context);
        }
Exemplo n.º 14
0
    public void GetBinding_ReturnsNullForUnprefixedTags(string tagName)
    {
        // Arrange
        var divDescriptor = TagHelperDescriptorBuilder.Create("foo1", "SomeAssembly")
                            .TagMatchingRuleDescriptor(rule => rule.RequireTagName(tagName))
                            .Build();
        var descriptors     = new[] { divDescriptor };
        var tagHelperBinder = new TagHelperBinder("th:", descriptors);

        // Act
        var bindingResult = tagHelperBinder.GetBinding(
            tagName: "div",
            attributes: Array.Empty <KeyValuePair <string, string> >(),
            parentTagName: "p",
            parentIsTagHelper: false);

        // Assert
        Assert.Null(bindingResult);
    }
Exemplo n.º 15
0
    public void GetBinding_ReturnsNullBindingResultPrefixAsTagName()
    {
        // Arrange
        var catchAllDescriptor = TagHelperDescriptorBuilder.Create("foo1", "SomeAssembly")
                                 .TagMatchingRuleDescriptor(rule => rule.RequireTagName(TagHelperMatchingConventions.ElementCatchAllName))
                                 .Build();
        var descriptors     = new[] { catchAllDescriptor };
        var tagHelperBinder = new TagHelperBinder("th", descriptors);

        // Act
        var bindingResult = tagHelperBinder.GetBinding(
            tagName: "th",
            attributes: Array.Empty <KeyValuePair <string, string> >(),
            parentTagName: "p",
            parentIsTagHelper: false);

        // Assert
        Assert.Null(bindingResult);
    }
        public DefaultVisualStudioDocumentTrackerTest()
        {
            RazorCoreContentType = Mock.Of <IContentType>(c => c.IsOfType(RazorLanguage.ContentType) && c.IsOfType(RazorConstants.LegacyContentType), MockBehavior.Strict);
            TextBuffer           = Mock.Of <ITextBuffer>(b => b.ContentType == RazorCoreContentType, MockBehavior.Strict);

            FilePath      = TestProjectData.SomeProjectFile1.FilePath;
            ProjectPath   = TestProjectData.SomeProject.FilePath;
            RootNamespace = TestProjectData.SomeProject.RootNamespace;

            ImportDocumentManager = new Mock <ImportDocumentManager>(MockBehavior.Strict).Object;
            Mock.Get(ImportDocumentManager).Setup(m => m.OnSubscribed(It.IsAny <VisualStudioDocumentTracker>())).Verifiable();
            Mock.Get(ImportDocumentManager).Setup(m => m.OnUnsubscribed(It.IsAny <VisualStudioDocumentTracker>())).Verifiable();

            var projectSnapshotManagerDispatcher = new Mock <ProjectSnapshotManagerDispatcher>(MockBehavior.Strict);

            projectSnapshotManagerDispatcher.Setup(d => d.AssertDispatcherThread(It.IsAny <string>())).Verifiable();
            WorkspaceEditorSettings = new DefaultWorkspaceEditorSettings(projectSnapshotManagerDispatcher.Object, Mock.Of <EditorSettingsManager>(MockBehavior.Strict));

            SomeTagHelpers = new List <TagHelperDescriptor>()
            {
                TagHelperDescriptorBuilder.Create("test", "test").Build(),
            };

            ProjectManager = new TestProjectSnapshotManager(Dispatcher, Workspace)
            {
                AllowNotifyListeners = true
            };

            HostProject        = new HostProject(ProjectPath, FallbackRazorConfiguration.MVC_2_1, RootNamespace);
            UpdatedHostProject = new HostProject(ProjectPath, FallbackRazorConfiguration.MVC_2_0, RootNamespace);
            OtherHostProject   = new HostProject(TestProjectData.AnotherProject.FilePath, FallbackRazorConfiguration.MVC_2_0, TestProjectData.AnotherProject.RootNamespace);

            DocumentTracker = new DefaultVisualStudioDocumentTracker(
                Dispatcher,
                JoinableTaskFactory.Context,
                FilePath,
                ProjectPath,
                ProjectManager,
                WorkspaceEditorSettings,
                Workspace,
                TextBuffer,
                ImportDocumentManager);
        }
        public DocumentStateTest()
        {
            TagHelperResolver = new TestTagHelperResolver();

            HostProject = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_2_0, TestProjectData.SomeProject.RootNamespace);
            HostProjectWithConfigurationChange = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0, TestProjectData.SomeProject.RootNamespace);
            ProjectWorkspaceState = new ProjectWorkspaceState(new[]
            {
                TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly").Build(),
            });

            SomeTagHelpers = new List <TagHelperDescriptor>();
            SomeTagHelpers.Add(TagHelperDescriptorBuilder.Create("Test1", "TestAssembly").Build());

            HostDocument = TestProjectData.SomeProjectFile1;

            Text       = SourceText.From("Hello, world!");
            TextLoader = () => Task.FromResult(TextAndVersion.Create(Text, VersionStamp.Create()));
        }
Exemplo n.º 18
0
        private static RazorSyntaxTree GetSyntaxTree(string source)
        {
            var taghelper = TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly")
                            .TagMatchingRuleDescriptor(rule => rule.RequireTagName("taghelper"))
                            .TypeName("TestTagHelper")
                            .Build();
            var engine = RazorEngine.CreateDesignTime(builder =>
            {
                builder.AddTagHelpers(taghelper);
            });

            var sourceDocument     = RazorSourceDocument.Create(source, "test.cshtml");
            var addTagHelperImport = RazorSourceDocument.Create("@addTagHelper *, TestAssembly", "import.cshtml");
            var codeDocument       = RazorCodeDocument.Create(sourceDocument, new[] { addTagHelperImport });

            engine.Process(codeDocument);

            return(codeDocument.GetSyntaxTree());
        }
    private void AddTagMatchingRules(INamedTypeSymbol type, TagHelperDescriptorBuilder descriptorBuilder)
    {
        var targetElementAttributes = type
                                      .GetAttributes()
                                      .Where(attribute => SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, _htmlTargetElementAttributeSymbol));

        // If there isn't an attribute specifying the tag name derive it from the name
        if (!targetElementAttributes.Any())
        {
            var name = type.Name;

            if (name.EndsWith(TagHelperNameEnding, StringComparison.OrdinalIgnoreCase))
            {
                name = name.Substring(0, name.Length - TagHelperNameEnding.Length);
            }

            descriptorBuilder.TagMatchingRule(ruleBuilder =>
            {
                var htmlCasedName   = HtmlConventions.ToHtmlCase(name);
                ruleBuilder.TagName = htmlCasedName;
            });

            return;
        }

        foreach (var targetElementAttribute in targetElementAttributes)
        {
            descriptorBuilder.TagMatchingRule(ruleBuilder =>
            {
                var tagName         = HtmlTargetElementAttribute_Tag(targetElementAttribute);
                ruleBuilder.TagName = tagName;

                var parentTag         = HtmlTargetElementAttribute_ParentTag(targetElementAttribute);
                ruleBuilder.ParentTag = parentTag;

                var tagStructure         = HtmlTargetElementAttribute_TagStructure(targetElementAttribute);
                ruleBuilder.TagStructure = tagStructure;

                var requiredAttributeString = HtmlTargetElementAttribute_Attributes(targetElementAttribute);
                RequiredAttributeParser.AddRequiredAttributes(requiredAttributeString, ruleBuilder);
            });
        }
    }
Exemplo n.º 20
0
        public SerializationTest()
        {
            var languageVersion = RazorLanguageVersion.Experimental;
            var extensions      = new RazorExtension[]
            {
                new SerializedRazorExtension("TestExtension"),
            };

            Configuration         = RazorConfiguration.Create(languageVersion, "Custom", extensions);
            ProjectWorkspaceState = new ProjectWorkspaceState(new[]
            {
                TagHelperDescriptorBuilder.Create("Test", "TestAssembly").Build(),
            },
                                                              LanguageVersion.LatestMajor);
            var converterCollection = new JsonConverterCollection();

            converterCollection.RegisterRazorConverters();
            Converters = converterCollection.ToArray();
        }
    private void AddAllowedChildren(INamedTypeSymbol type, TagHelperDescriptorBuilder builder)
    {
        var restrictChildrenAttribute = type.GetAttributes().Where(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, _restrictChildrenAttributeSymbol)).FirstOrDefault();

        if (restrictChildrenAttribute == null)
        {
            return;
        }

        builder.AllowChildTag(childTagBuilder => childTagBuilder.Name = (string)restrictChildrenAttribute.ConstructorArguments[0].Value);

        if (restrictChildrenAttribute.ConstructorArguments.Length == 2)
        {
            foreach (var value in restrictChildrenAttribute.ConstructorArguments[1].Values)
            {
                builder.AllowChildTag(childTagBuilder => childTagBuilder.Name = (string)value.Value);
            }
        }
    }
Exemplo n.º 22
0
        private static TagHelperDescriptor CreateTagHelperDescriptor(
            string kind,
            string tagName,
            string typeName,
            string assemblyName,
            IEnumerable <Action <BoundAttributeDescriptorBuilder> > attributes    = null,
            IEnumerable <Action <TagMatchingRuleDescriptorBuilder> > ruleBuilders = null,
            Action <TagHelperDescriptorBuilder> configureAction = null)
        {
            var builder = TagHelperDescriptorBuilder.Create(kind, typeName, assemblyName);

            builder.SetTypeName(typeName);

            if (attributes != null)
            {
                foreach (var attributeBuilder in attributes)
                {
                    builder.BoundAttributeDescriptor(attributeBuilder);
                }
            }

            if (ruleBuilders != null)
            {
                foreach (var ruleBuilder in ruleBuilders)
                {
                    builder.TagMatchingRuleDescriptor(innerRuleBuilder => {
                        innerRuleBuilder.RequireTagName(tagName);
                        ruleBuilder(innerRuleBuilder);
                    });
                }
            }
            else
            {
                builder.TagMatchingRuleDescriptor(ruleBuilder => ruleBuilder.RequireTagName(tagName));
            }

            configureAction?.Invoke(builder);

            var descriptor = builder.Build();

            return(descriptor);
        }
        public void GetElementCompletions_CapturesAllAllowedChildTagsFromParentTagHelpers_AllTagHelpers()
        {
            // Arrange
            var documentDescriptors = new[]
            {
                TagHelperDescriptorBuilder.Create("BoldParentCatchAll", "TestAssembly")
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("*"))
                .AllowChildTag("strong")
                .AllowChildTag("div")
                .AllowChildTag("b")
                .Build(),
                TagHelperDescriptorBuilder.Create("BoldParent", "TestAssembly")
                .TagMatchingRuleDescriptor(rule => rule.RequireTagName("div"))
                .AllowChildTag("b")
                .AllowChildTag("bold")
                .Build(),
            };
            var expectedCompletions = ElementCompletionResult.Create(new Dictionary <string, HashSet <TagHelperDescriptor> >()
            {
                ["strong"] = new HashSet <TagHelperDescriptor> {
                    documentDescriptors[0]
                },
                ["b"] = new HashSet <TagHelperDescriptor> {
                    documentDescriptors[0]
                },
                ["bold"] = new HashSet <TagHelperDescriptor> {
                    documentDescriptors[0]
                },
                ["div"] = new HashSet <TagHelperDescriptor> {
                    documentDescriptors[0], documentDescriptors[1]
                },
            });

            var completionContext = BuildElementCompletionContext(documentDescriptors, Enumerable.Empty <string>(), containingTagName: "div");
            var service           = CreateTagHelperCompletionFactsService();

            // Act
            var completions = service.GetElementCompletions(completionContext);

            // Assert
            AssertCompletionsAreEquivalent(expectedCompletions, completions);
        }
        private static IEnumerable <TagHelperDescriptor> CreateRazorComponentTagHelperDescriptors(string assemblyName, string namespaceName, string tagName)
        {
            var fullyQualifiedName = $"{namespaceName}.{tagName}";
            var builder            = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, fullyQualifiedName, assemblyName);

            builder.TagMatchingRule(rule => rule.TagName = tagName);
            builder.SetTypeName(fullyQualifiedName);
            builder.SetTypeNameIdentifier(tagName);
            builder.SetTypeNamespace(namespaceName);
            yield return(builder.Build());

            var fullyQualifiedBuilder = TagHelperDescriptorBuilder.Create(ComponentMetadata.Component.TagHelperKind, fullyQualifiedName, assemblyName);

            fullyQualifiedBuilder.TagMatchingRule(rule => rule.TagName = fullyQualifiedName);
            fullyQualifiedBuilder.SetTypeName(fullyQualifiedName);
            fullyQualifiedBuilder.SetTypeNameIdentifier(tagName);
            fullyQualifiedBuilder.SetTypeNamespace(namespaceName);
            fullyQualifiedBuilder.AddMetadata(ComponentMetadata.Component.NameMatchKey, ComponentMetadata.Component.FullyQualifiedNameMatch);
            yield return(fullyQualifiedBuilder.Build());
        }
        public DefaultProjectSnapshotTest()
        {
            TagHelperResolver = new TestTagHelperResolver();

            HostProject           = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_2_0, TestProjectData.SomeProject.RootNamespace);
            ProjectWorkspaceState = new ProjectWorkspaceState(new[]
            {
                TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly").Build(),
            },
                                                              default);

            Documents = new HostDocument[]
            {
                TestProjectData.SomeProjectFile1,
                TestProjectData.SomeProjectFile2,

                // linked file
                TestProjectData.AnotherProjectNestedFile3,
            };
        }
        private static void AddTagMatchingRules(Type type, TagHelperDescriptorBuilder descriptorBuilder)
        {
            var targetElementAttributes = type.GetCustomAttributes <HtmlTargetElementAttribute>();

            // If there isn't an attribute specifying the tag name derive it from the name
            if (!targetElementAttributes.Any())
            {
                var name = type.Name;

                if (name.EndsWith("TagHelper", StringComparison.OrdinalIgnoreCase))
                {
                    name = name.Substring(0, name.Length - "TagHelper".Length);
                }

                descriptorBuilder.TagMatchingRule(ruleBuilder =>
                {
                    var htmlCasedName   = HtmlConventions.ToHtmlCase(name);
                    ruleBuilder.TagName = htmlCasedName;
                });

                return;
            }

            foreach (var targetElementAttribute in targetElementAttributes)
            {
                descriptorBuilder.TagMatchingRule(ruleBuilder =>
                {
                    var tagName         = targetElementAttribute.Tag;
                    ruleBuilder.TagName = tagName;

                    var parentTag         = targetElementAttribute.ParentTag;
                    ruleBuilder.ParentTag = parentTag;

                    var tagStructure         = targetElementAttribute.TagStructure;
                    ruleBuilder.TagStructure = (Microsoft.AspNetCore.Razor.Language.TagStructure)tagStructure;

                    var requiredAttributeString = targetElementAttribute.Attributes;
                    RequiredAttributeParser.AddRequiredAttributes(requiredAttributeString, ruleBuilder);
                });
            }
        }
        private TagHelperDescriptor CreateChildContentDescriptor(BlazorSymbols symbols, TagHelperDescriptor component, BoundAttributeDescriptor attribute)
        {
            var typeName     = component.GetTypeName() + "." + attribute.Name;
            var assemblyName = component.AssemblyName;

            var builder = TagHelperDescriptorBuilder.Create(BlazorMetadata.ChildContent.TagHelperKind, typeName, assemblyName);

            builder.SetTypeName(typeName);

            // This opts out this 'component' tag helper for any processing that's specific to the default
            // Razor ITagHelper runtime.
            builder.Metadata[TagHelperMetadata.Runtime.Name] = BlazorMetadata.ChildContent.RuntimeName;

            // Opt out of processing as a component. We'll process this specially as part of the component's body.
            builder.Metadata[BlazorMetadata.SpecialKindKey] = BlazorMetadata.ChildContent.TagHelperKind;

            var xml = attribute.Documentation;

            if (!string.IsNullOrEmpty(xml))
            {
                builder.Documentation = xml;
            }

            // Child content matches the property name, but only as a direct child of the component.
            builder.TagMatchingRule(r =>
            {
                r.TagName   = attribute.Name;
                r.ParentTag = component.TagMatchingRules.First().TagName;
            });

            if (attribute.IsParameterizedChildContentProperty())
            {
                // For child content attributes with a parameter, synthesize an attribute that allows you to name
                // the parameter.
                CreateContextParameter(builder, attribute.Name);
            }

            var descriptor = builder.Build();

            return(descriptor);
        }
        private void EnsureMatchings()
        {
            if (_matchings != null)
            {
                return;
            }

            lock (this)
            {
                if (_matchings == null)
                {
                    var feature = new TagHelperFeature();
                    _partManager.PopulateFeature(feature);

                    var matchings = new List <LiquidTagHelperMatching>();

                    foreach (var tagHelper in feature.TagHelpers)
                    {
                        var matching = _allMatchings.GetOrAdd(tagHelper.AsType(), type =>
                        {
                            var descriptorBuilder = TagHelperDescriptorBuilder.Create(
                                type.FullName, type.Assembly.GetName().Name);

                            descriptorBuilder.SetTypeName(type.FullName);
                            AddTagMatchingRules(type, descriptorBuilder);
                            var descriptor = descriptorBuilder.Build();

                            return(new LiquidTagHelperMatching(
                                       descriptor.Name,
                                       descriptor.AssemblyName,
                                       descriptor.TagMatchingRules
                                       ));
                        });

                        matchings.Add(matching);
                    }

                    _matchings = matchings;
                }
            }
        }
        private static void ReadAllowedChildTag(JsonReader reader, TagHelperDescriptorBuilder builder)
        {
            if (!reader.Read())
            {
                return;
            }

            if (reader.TokenType != JsonToken.StartObject)
            {
                return;
            }

            builder.AllowChildTag(childTag =>
            {
                reader.ReadProperties(propertyName =>
                {
                    switch (propertyName)
                    {
                    case nameof(AllowedChildTagDescriptor.Name):
                        if (reader.Read())
                        {
                            var name      = (string)reader.Value;
                            childTag.Name = name;
                        }
                        break;

                    case nameof(AllowedChildTagDescriptor.DisplayName):
                        if (reader.Read())
                        {
                            var displayName      = (string)reader.Value;
                            childTag.DisplayName = displayName;
                        }
                        break;

                    case nameof(AllowedChildTagDescriptor.Diagnostics):
                        ReadDiagnostics(reader, childTag.Diagnostics);
                        break;
                    }
                });
            });
        }
Exemplo n.º 30
0
        private static RazorCodeDocument GetCodeDocument(string source)
        {
            var taghelper = TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly")
                            .BoundAttributeDescriptor(attr => attr.Name("show").TypeName("System.Boolean"))
                            .BoundAttributeDescriptor(attr => attr.Name("id").TypeName("System.Int32"))
                            .TagMatchingRuleDescriptor(rule => rule.RequireTagName("taghelper"))
                            .TypeName("TestTagHelper")
                            .Build();
            var engine = RazorEngine.CreateDesignTime(builder =>
            {
                builder.AddTagHelpers(taghelper);
            });

            var sourceDocument     = RazorSourceDocument.Create(source, "test.cshtml");
            var addTagHelperImport = RazorSourceDocument.Create("@addTagHelper *, TestAssembly", "import.cshtml");
            var codeDocument       = RazorCodeDocument.Create(sourceDocument, new[] { addTagHelperImport });

            engine.Process(codeDocument);

            return(codeDocument);
        }