示例#1
0
        public void DetectsWhenPageContentIsNotAlreadySet()
        {
            var profile = TestProfile.CreateEmpty();

            profile.ViewGeneration.XamlFileSuffix      = "Page";
            profile.ViewGeneration.ViewModelFileSuffix = "ViewModel";
            profile.Datacontext.CodeBehindPageContent  = @"Public ReadOnly Property ViewModel As $viewmodelclass$
    Get
        Return New $viewmodelclass$
    End Get
End Property";

            var logger = DefaultTestLogger.Create();

            var vs = new TestVisualStudioAbstraction
            {
                ActiveDocumentFileName = "TestPage.xaml.vb",
                ActiveDocumentText     = @"Public NotInheritable Class TestPage
    Inherits Page

    Sub New()
        InitializeComponent()
    End Sub
End Class",
            };

            var fs = new TestFileSystem();

            var sut = new SetDataContextCommandLogic(profile, logger, vs, fs);

            var result = sut.ShouldEnableCommand();

            Assert.IsTrue(result);
        }
        public void OnlyElementsThatContainAreAnalyzed()
        {
            var xaml = @"
<StackPanel>
    <TextBlock Text=""Something"" />
    <TextBlock Text=""{Binding SomeVmProperty}"" />
    <TextBlock Text=""{x:Bind}"" />
</StackPanel>";

            var result = new RapidXamlDocument();

            var snapshot = new FakeTextSnapshot(xaml.Length);
            var logger   = DefaultTestLogger.Create();
            var vsa      = new TestVisualStudioAbstraction();

            var processors = RapidXamlDocument.WrapCustomProcessors(
                new List <ICustomAnalyzer> {
                new AnyOrChildrenContainingCustomAnalyzer()
            },
                ProjectType.Unknown,
                string.Empty,
                logger,
                vsa);

            XamlElementExtractor.Parse("Generic.xaml", snapshot, xaml, processors.ToList(), result.Tags, null, null, logger);

            // This will be two becuase called for the 2nd TextBlock and also the containing StackPanel
            Assert.AreEqual(2, AnyOrChildrenContainingCustomAnalyzer.AnalyzeCallCount);
        }
        protected void EachPositionBetweenStarsShouldProduceExpected(string code, ParserOutput expected, bool isCSharp, Profile profileOverload)
        {
            this.EnsureTwoStars(code);

            var(startPos, endPos, actualCode) = this.GetCodeAndCursorRange(code);

            var syntaxTree = isCSharp ? CSharpSyntaxTree.ParseText(actualCode)
                                      : VisualBasicSyntaxTree.ParseText(actualCode);

            Assert.IsNotNull(syntaxTree);

            var semModel = isCSharp ? CSharpCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true)
                                    : VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true);

            var positionsTested = 0;

            for (var pos = startPos; pos < endPos; pos++)
            {
                var indent = new TestVisualStudioAbstraction().XamlIndent;
                var parser = isCSharp ? new CSharpParser(DefaultTestLogger.Create(), indent, profileOverload) as IDocumentParser
                                      : new VisualBasicParser(DefaultTestLogger.Create(), indent, profileOverload);

                var actual = parser.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos);

                Assert.AreEqual(expected.OutputType, actual.OutputType, $"Failure at {pos} ({startPos}-{endPos})");
                Assert.AreEqual(expected.Name, actual.Name, $"Failure at {pos} ({startPos}-{endPos})");
                StringAssert.AreEqual(expected.Output, actual.Output, $"Failure at {pos} ({startPos}-{endPos})");

                positionsTested += 1;
            }

            this.TestContext.WriteLine($"{positionsTested} different positions tested.");
        }
        public void CanGetXmlns_WhenSplitOverMultipleLines()
        {
            var tags = new TagList();

            var xaml = "<Page" +
                       Environment.NewLine + " xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
                       Environment.NewLine + " xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"" +
                       Environment.NewLine + " xmlns:local" +
                       Environment.NewLine + "=\"using:XamlChangeTest\"" +
                       Environment.NewLine + " xmlns:d=" +
                       Environment.NewLine + "\"http://schemas.microsoft.com/expression/blend/2008\"" +
                       Environment.NewLine + " xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\">" +
                       Environment.NewLine + "    <TestElement />" +
                       Environment.NewLine + "</Page>";

            var snapshot = new FakeTextSnapshot(xaml.Length);
            var vsa      = new TestVisualStudioAbstraction();
            var logger   = DefaultTestLogger.Create();

            var analyzer = new XmnlsCounterAnalyzer();

            var processors = new List <(string, XamlElementProcessor)>
            {
                (analyzer.TargetType(), new CustomProcessorWrapper(analyzer, ProjectType.Any, string.Empty, logger, vsa)),
            };

            XamlElementExtractor.Parse("testfile.xaml", snapshot, xaml, processors, tags, null, RapidXamlDocument.GetEveryElementProcessor(ProjectType.Any, null, vsa), logger);

            Assert.AreEqual(5, analyzer.Count);

            foreach (var key in analyzer.Xmlns.Keys)
            {
                Assert.IsFalse(string.IsNullOrEmpty(analyzer.Xmlns[key]), $"No value for key '{key}'");
            }
        }
示例#5
0
        public void CanDetectWhereAndWhatToInsert()
        {
            var profile = TestProfile.CreateEmpty();

            profile.Datacontext.XamlPageAttribute = "DataContext=\"HasBeenSet\"";

            var logger = DefaultTestLogger.Create();

            var activeDocText = "<Page"
                                + Environment.NewLine + "    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\""
                                + Environment.NewLine + "    >"
                                + Environment.NewLine + "    <!-- Content would go here -->"
                                + Environment.NewLine + "</Page>";

            var vs = new TestVisualStudioAbstraction
            {
                ActiveDocumentFileName = "test.xaml",
                ActiveDocumentText     = activeDocText,
            };

            var fs = new TestFileSystem();

            var sut = new SetDataContextCommandLogic(profile, logger, vs, fs);

            var result = sut.GetPageAttributeToAdd("TestViewModel", "Tests");

            Assert.IsTrue(result.anythingToAdd);
            Assert.AreEqual(2, result.lineNoToAddAfter);
            Assert.AreEqual($"{Environment.NewLine}    DataContext=\"HasBeenSet\"", result.contentToAdd);
        }
示例#6
0
        public void AnalyzerGetsCorrectContent()
        {
            var xaml = @"
<StackPanel>
    <TextBlock>&lt;Page.Resources>NONE&lt;/Page.Resources></TextBlock>
</StackPanel>";

            var result = new RapidXamlDocument();

            var snapshot = new FakeTextSnapshot(xaml.Length);
            var logger   = DefaultTestLogger.Create();
            var vsa      = new TestVisualStudioAbstraction();

            var analyzer = new XmlEncodingTestAnalyzer();

            var processors = RapidXamlDocument.WrapCustomProcessors(
                new List <ICustomAnalyzer> {
                analyzer
            },
                ProjectType.Unknown,
                string.Empty,
                logger,
                vsa);

            XamlElementExtractor.Parse("Generic.xaml", snapshot, xaml, processors.ToList(), result.Tags, null, null, logger);

            Assert.AreEqual("&lt;Page.Resources>NONE&lt;/Page.Resources>", analyzer.Element.Content);
        }
        public void DetectsWhenConstructorContentIsNotAlreadySet()
        {
            var profile = TestProfile.CreateEmpty();

            profile.Datacontext.CodeBehindConstructorContent = "this.DataContext = this.ViewModel;";

            var logger = DefaultTestLogger.Create();

            var vs = new TestVisualStudioAbstraction
            {
                ActiveDocumentFileName = "test.xaml.cs",
                ActiveDocumentText     = @"class TestPage
{
    public TestPage()
    {
        this.Initialize();
    }
}",
            };

            var fs = new TestFileSystem();

            var sut = new SetDataContextCommandLogic(profile, logger, vs, fs);

            var result = sut.ShouldEnableCommand();

            Assert.IsTrue(result);
        }
        public void MultipleNameContainsIsIdentified()
        {
            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, this.testProfile);
            var result = cpb.GetPropertyOutput("string", "EnteredPassword", isReadOnly: false);

            Assert.AreEqual(ReadWritePasswordStringOutput.Replace("$name$", "EnteredPassword"), result);
        }
        public void ReadOnlyTakesPriorityOverContains()
        {
            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, this.testProfile);
            var result = cpb.GetPropertyOutput("string", "EnteredPwd", isReadOnly: true);

            Assert.AreEqual(ReadonlyStringOutput.Replace("$name$", "EnteredPwd"), result);
        }
        protected void PositionAtStarShouldProduceExpectedUsingAdditonalLibraries(string code, AnalyzerOutput expected, bool isCSharp, Profile profileOverload, params string[] additionalLibraryPaths)
        {
            var pos = code.IndexOf("*", StringComparison.Ordinal);

            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            var language = isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic;
            var fileExt  = isCSharp ? "cs" : "vb";

            var solution = new AdhocWorkspace().CurrentSolution
                           .AddProject(projectId, "MyProject", "MyProject", language)
                           .AddDocument(documentId, $"MyFile.{fileExt}", code.Replace("*", string.Empty));

            foreach (var libPath in additionalLibraryPaths)
            {
                var lib = MetadataReference.CreateFromFile(libPath);

                solution = solution.AddMetadataReference(projectId, lib);
            }

            var document = solution.GetDocument(documentId);

            var semModel   = document.GetSemanticModelAsync().Result;
            var syntaxTree = document.GetSyntaxTreeAsync().Result;

            var analyzer = isCSharp ? new CSharpAnalyzer(DefaultTestLogger.Create()) as IDocumentAnalyzer
                                    : new VisualBasicAnalyzer(DefaultTestLogger.Create());

            var actual = analyzer.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos, new TestVisualStudioAbstraction().XamlIndent, profileOverload);

            Assert.AreEqual(expected.OutputType, actual.OutputType);
            Assert.AreEqual(expected.Name, actual.Name);
            StringAssert.AreEqual(expected.Output, actual.Output);
        }
示例#11
0
        public void AnalyzeAllCommaSeparatedTypes()
        {
            var xaml = @"
<StackPanel>
    <TextBlock />
    <TextBox />
</StackPanel>";

            var result = new RapidXamlDocument();

            var snapshot = new FakeTextSnapshot(xaml.Length);
            var logger   = DefaultTestLogger.Create();
            var vsa      = new TestVisualStudioAbstraction();

            var processors = RapidXamlDocument.WrapCustomProcessors(
                new List <ICustomAnalyzer> {
                new TextTypesCustomAnalyzer()
            },
                ProjectType.Unknown,
                string.Empty,
                logger,
                vsa);

            XamlElementExtractor.Parse("Generic.xaml", snapshot, xaml, processors.ToList(), result.Tags, null, null, logger);

            Assert.AreEqual(2, result.Tags.Count());
        }
        protected void EachPositionBetweenStarsShouldProduceExpected(string code, AnalyzerOutput expected, bool isCSharp, Profile profileOverload)
        {
            var startPos = code.IndexOf("*", StringComparison.Ordinal);
            var endPos   = code.LastIndexOf("*", StringComparison.Ordinal) - 1;

            var syntaxTree = isCSharp ? CSharpSyntaxTree.ParseText(code.Replace("*", string.Empty))
                                      : VisualBasicSyntaxTree.ParseText(code.Replace("*", string.Empty));

            Assert.IsNotNull(syntaxTree);

            var semModel = isCSharp ? CSharpCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true)
                                    : VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true);

            var positionsTested = 0;

            for (var pos = startPos; pos < endPos; pos++)
            {
                var analyzer = isCSharp ? new CSharpAnalyzer(DefaultTestLogger.Create()) as IDocumentAnalyzer : new VisualBasicAnalyzer(DefaultTestLogger.Create());

                var actual = analyzer.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos, new TestVisualStudioAbstraction().XamlIndent, profileOverload);

                Assert.AreEqual(expected.OutputType, actual.OutputType, $"Failure at {pos} ({startPos}-{endPos})");
                Assert.AreEqual(expected.Name, actual.Name, $"Failure at {pos} ({startPos}-{endPos})");
                StringAssert.AreEqual(expected.Output, actual.Output, $"Failure at {pos} ({startPos}-{endPos})");

                positionsTested += 1;
            }

            this.TestContext.WriteLine($"{positionsTested} different positions tested.");
        }
示例#13
0
        public void DetectsWhenConstructorContentIsNotAlreadySet()
        {
            var profile = TestProfile.CreateEmpty();

            profile.Datacontext.CodeBehindConstructorContent = "DataContext = ViewModel";

            var logger = DefaultTestLogger.Create();

            var vs = new TestVisualStudioAbstraction
            {
                ActiveDocumentFileName = "TestPage.xaml.vb",
                ActiveDocumentText     = @"Public NotInheritable Class TestPage
    Inherits Page

    Sub New()
        InitializeComponent()
    End Sub
End Class",
            };

            var fs = new TestFileSystem();

            var sut = new SetDataContextCommandLogic(profile, logger, vs, fs);

            var result = sut.ShouldEnableCommand();

            Assert.IsTrue(result);
        }
示例#14
0
        public void CanDetectWhereAndWhenToInsertConstructorAndPageContentWhenConstructorExists()
        {
            var pageContent = "Public ReadOnly Property ViewModel As $viewmodelclass$"
                              + Environment.NewLine + "    Get"
                              + Environment.NewLine + "        Return New $viewmodelclass$"
                              + Environment.NewLine + "    End Get"
                              + Environment.NewLine + "End Property";

            var profile = TestProfile.CreateEmpty();

            profile.ViewGeneration.XamlFileSuffix            = "Page";
            profile.ViewGeneration.ViewModelFileSuffix       = "ViewModel";
            profile.Datacontext.CodeBehindConstructorContent = "DataContext = ViewModel";
            profile.Datacontext.CodeBehindPageContent        = pageContent;

            var logger = DefaultTestLogger.Create();

            var fs = new TestFileSystem
            {
                FileText = @"Public NotInheritable Class TestPage
    Inherits Page

    Sub New()
        InitializeComponent()
    End Sub
End Class",
            };

            var synTree = VisualBasicSyntaxTree.ParseText(fs.FileText);

            var vs = new TestVisualStudioAbstraction
            {
                ActiveDocumentFileName = "TestPage.xaml.vb",
                ActiveDocumentText     = fs.FileText,
                SyntaxTree             = synTree,
                DocumentIsCSharp       = false,
            };

            var sut = new SetDataContextCommandLogic(profile, logger, vs, fs);

            var documentRoot = synTree.GetRoot();

            var result = sut.GetCodeBehindContentToAdd("TestPage", "TestViewModel", "TestVmNamespace", documentRoot);

            Assert.IsTrue(result[0].anythingToAdd);
            Assert.AreEqual(5, result[0].lineNoToAddAfter);
            StringAssert.AreEqual($"{Environment.NewLine}{Environment.NewLine}DataContext = ViewModel", result[0].contentToAdd);

            var expectedContent = ""
                                  + Environment.NewLine + ""
                                  + Environment.NewLine + "Public ReadOnly Property ViewModel As TestViewModel"
                                  + Environment.NewLine + "    Get"
                                  + Environment.NewLine + "        Return New TestViewModel"
                                  + Environment.NewLine + "    End Get"
                                  + Environment.NewLine + "End Property";

            Assert.IsTrue(result[1].anythingToAdd);
            Assert.AreEqual(8, result[1].lineNoToAddAfter);
            StringAssert.AreEqual(expectedContent, result[1].contentToAdd);
        }
        public async Task HandleFileNotContainingClassDefinition()
        {
            var profile = this.GetDefaultTestProfile();

            profile.ViewGeneration.AllInSameProject       = true;
            profile.ViewGeneration.ViewModelDirectoryName = "Files";
            profile.ViewGeneration.ViewModelFileSuffix    = "ViewModel";
            profile.ViewGeneration.XamlFileDirectoryName  = "Files";
            profile.ViewGeneration.XamlFileSuffix         = "Page";

            var fs = new TestFileSystem
            {
                FileExistsResponse = false,
                FileText           = " // There's nothing in this file apart from a comment",
            };

            var synTree  = CSharpSyntaxTree.ParseText(fs.FileText);
            var semModel = CSharpCompilation.Create(string.Empty).AddSyntaxTrees(synTree).GetSemanticModel(synTree, ignoreAccessibility: true);

            var vsa = new TestVisualStudioAbstraction
            {
                SyntaxTree    = synTree,
                SemanticModel = semModel,
                ActiveProject = new ProjectWrapper()
                {
                    Name = "App", FileName = @"C:\Test\App\App.csproj"
                },
            };

            var sut = new CreateViewCommandLogic(profile, DefaultTestLogger.Create(), vsa, fs);

            await sut.ExecuteAsync(@"C:\Test\App\Files\TestViewModel.cs");

            Assert.IsFalse(sut.CreateView);
        }
        public void TypeNameIsCaseInsensitive()
        {
            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, this.testProfile);
            var result = cpb.GetPropertyOutput("INT", "number1", isReadOnly: false);

            Assert.AreEqual(ReadWriteNumberIntOutput, result);
        }
示例#17
0
        public async Task FileExistsAndDoNotOverwriteMeansNoNewFileCreatedAsync()
        {
            var profile = this.GetDefaultTestProfile();

            profile.ViewGeneration.AllInSameProject       = true;
            profile.ViewGeneration.ViewModelDirectoryName = "ViewModels";
            profile.ViewGeneration.ViewModelFileSuffix    = "ViewModel";
            profile.ViewGeneration.XamlFileDirectoryName  = "Views";
            profile.ViewGeneration.XamlFileSuffix         = "Page";

            var fs = new TestFileSystem
            {
                FileExistsResponse = true,
                FileText           = " public class TestViewModel { public string OnlyProperty { get; set;} }",
            };

            var synTree  = CSharpSyntaxTree.ParseText(fs.FileText);
            var semModel = CSharpCompilation.Create(string.Empty).AddSyntaxTrees(synTree).GetSemanticModel(synTree, ignoreAccessibility: true);

            var vsa = new TestVisualStudioAbstraction
            {
                UserConfirmsResult = false,
                SyntaxTree         = synTree,
                SemanticModel      = semModel,
                ActiveProject      = new ProjectWrapper()
                {
                    Name = "App", FileName = @"C:\Test\App\App.csproj"
                },
            };
            var sut = new CreateViewCommandLogic(profile, DefaultTestLogger.Create(), vsa, fs);

            await sut.ExecuteAsync(@"C:\Test\App\ViewModels\TestViewModel.cs");

            Assert.IsFalse(sut.CreateView);
        }
        public void GetFallbackIfTypeNotMapped()
        {
            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, this.testProfile);
            var result = cpb.GetPropertyOutput("bool", "IsAdmin", isReadOnly: false);

            Assert.AreEqual(FallbackOutput, result);
        }
示例#19
0
        private void AssertSingleTagAtLocation(string xaml, ICustomAnalyzer analyzer, int startPoint)
        {
            var tags   = new TagList();
            var vsa    = new TestVisualStudioAbstraction();
            var logger = DefaultTestLogger.Create();

            var processors = new List <(string, XamlElementProcessor)>
            {
                (analyzer.TargetType(), new CustomProcessorWrapper(analyzer, ProjectType.Uwp, string.Empty, logger, vsa)),
            };

            var snapshot = new FakeTextSnapshot(xaml.Length);

            XamlElementExtractor.Parse(
                "SomeTestFile.xaml",
                snapshot,
                xaml,
                processors,
                tags,
                null,
                null,
                logger);

            Assert.AreEqual(1, tags.Count);
            Assert.AreEqual(startPoint, (tags[0] as CustomAnalysisTag).Span.Start);
        }
        public void CanHandleMultipleNumberReplacements()
        {
            var gridProfile = new Profile
            {
                Name              = "GridTestProfile",
                ClassGrouping     = "Grid",
                FallbackOutput    = "<TextBlock Text=\"FALLBACK_$name$\" />",
                SubPropertyOutput = "<TextBlock Text=\"SUBPROP_$name$\" />",
                Mappings          = new ObservableCollection <Mapping>
                {
                    new Mapping
                    {
                        Type         = StringPropertyName,
                        NameContains = "",
                        Output       = "<TextBlock Text=\"$name$\" Grid.Row=\"$incint$\" /><TextBlock Text=\"$name$\" Grid.Row=\"$incint$\" />",
                        IfReadOnly   = false,
                    },
                },
            };

            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, gridProfile);
            var result = cpb.GetPropertyOutput(StringPropertyName, "MyProperty", false);

            var expected = "<TextBlock Text=\"MyProperty\" Grid.Row=\"1\" />" + Environment.NewLine +
                           "<TextBlock Text=\"MyProperty\" Grid.Row=\"2\" />";

            StringAssert.AreEqual(expected, result);
        }
        public void PassMultipleXmlnsToAnalyzers_SingleQuotes()
        {
            var tags = new TagList();

            var xaml = "<Page" +
                       Environment.NewLine + " xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'" +
                       Environment.NewLine + " xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'" +
                       Environment.NewLine + " xmlns:local='using:XamlChangeTest'" +
                       Environment.NewLine + " xmlns:d='http://schemas.microsoft.com/expression/blend/2008'" +
                       Environment.NewLine + " xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'>" +
                       Environment.NewLine + "    <TestElement />" +
                       Environment.NewLine + "</Page>";

            var snapshot = new FakeTextSnapshot(xaml.Length);
            var vsa      = new TestVisualStudioAbstraction();
            var logger   = DefaultTestLogger.Create();

            var analyzer = new XmnlsCounterAnalyzer();

            var processors = new List <(string, XamlElementProcessor)>
            {
                (analyzer.TargetType(), new CustomProcessorWrapper(analyzer, ProjectType.Any, string.Empty, logger, vsa)),
            };

            XamlElementExtractor.Parse("testfile.xaml", snapshot, xaml, processors, tags, null, RapidXamlDocument.GetEveryElementProcessor(ProjectType.Any, null, vsa), logger);

            Assert.AreEqual(5, analyzer.Count);
            Assert.AreEqual("http://schemas.microsoft.com/winfx/2006/xaml/presentation", analyzer.Xmlns[string.Empty]);
        }
        public void SpecificGenericsMatchBeforeWildCard()
        {
            var wildcardGenericsProfile = new Profile
            {
                Name           = "wildcardGenericsProfile",
                ClassGrouping  = "Grid",
                FallbackOutput = "<Fallback />",
                Mappings       = new ObservableCollection <Mapping>
                {
                    new Mapping
                    {
                        Type         = "List<T>",
                        NameContains = "",
                        Output       = "<Wildcard />",
                        IfReadOnly   = false,
                    },
                    new Mapping
                    {
                        Type         = "List<string>",
                        NameContains = "",
                        Output       = "<ListOfStrings />",
                        IfReadOnly   = false,
                    },
                },
            };

            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, wildcardGenericsProfile);
            var result = cpb.GetPropertyOutput("List<string>", "MyProperty", isReadOnly: false);

            Assert.AreEqual("<ListOfStrings />", result);
        }
示例#23
0
        public void CanDetectIfNotAlreadySet()
        {
            var profile = TestProfile.CreateEmpty();

            profile.Datacontext.XamlPageAttribute = "DataContext=\"HasBeenSet\"";

            var logger = DefaultTestLogger.Create();

            var vs = new TestVisualStudioAbstraction
            {
                ActiveDocumentFileName = "test.xaml",
                ActiveDocumentText     = @"<Page
    >
    <!-- Content would go here -->
</Page>",
            };

            var fs = new TestFileSystem();

            var sut = new SetDataContextCommandLogic(profile, logger, vs, fs);

            var result = sut.ShouldEnableCommand();

            Assert.IsTrue(result);
        }
        public void GetsNonFilteredOutputIfNameDoesntMatch()
        {
            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, this.testProfile);
            var result = cpb.GetPropertyOutput("string", "MyProperty", isReadOnly: false);

            Assert.AreEqual(ReadWriteStringOutput.Replace("$name$", "MyProperty"), result);
        }
        public async Task FileJustContainsComments()
        {
            var profile = this.GetDefaultTestProfile();

            profile.ViewGeneration.AllInSameProject       = true;
            profile.ViewGeneration.ViewModelDirectoryName = "Files";
            profile.ViewGeneration.ViewModelFileSuffix    = "ViewModel";
            profile.ViewGeneration.XamlFileDirectoryName  = "Files";
            profile.ViewGeneration.XamlFileSuffix         = "Page";

            var fs = new TestFileSystem
            {
                FileExistsResponse = false,
                FileText           = @" ' Just comments in this file",
            };

            var synTree  = VisualBasicSyntaxTree.ParseText(fs.FileText);
            var semModel = VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(synTree).GetSemanticModel(synTree, ignoreAccessibility: true);

            var vsa = new TestVisualStudioAbstraction
            {
                SyntaxTree    = synTree,
                SemanticModel = semModel,
                ActiveProject = new ProjectWrapper()
                {
                    Name = "App", FileName = @"C:\Test\App\App.vbproj"
                },
            };

            var sut = new CreateViewCommandLogic(DefaultTestLogger.Create(), vsa, fs, profile);

            await sut.ExecuteAsync(@"C:\Test\App\Files\TestViewModel.vb");

            Assert.IsFalse(sut.CreateView);
        }
        public void ReadWritePropertyIsIdentified()
        {
            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, this.testProfile);
            var result = cpb.GetPropertyOutput("string", "AnotherProperty", isReadOnly: true);

            Assert.AreEqual(ReadonlyStringOutput.Replace("$name$", "AnotherProperty"), result);
        }
        protected void PositionAtStarShouldProduceExpectedUsingAdditonalFiles(string code, AnalyzerOutput expected, bool isCSharp, Profile profileOverload, params string[] additionalCode)
        {
            this.EnsureOneStar(code);

            var(pos, actualCode) = this.GetCodeAndCursorPos(code);

            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            var language = isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic;
            var fileExt  = isCSharp ? "cs" : "vb";

            var solution = new AdhocWorkspace().CurrentSolution
                           .AddProject(projectId, "MyProject", "MyProject", language)
                           .AddDocument(documentId, $"MyFile.{fileExt}", actualCode);

            foreach (var addCode in additionalCode)
            {
                solution = solution.AddDocument(DocumentId.CreateNewId(projectId), $"{System.IO.Path.GetRandomFileName()}.{fileExt}", addCode);
            }

            var document = solution.GetDocument(documentId);

            var semModel   = document.GetSemanticModelAsync().Result;
            var syntaxTree = document.GetSyntaxTreeAsync().Result;

            var indent = new TestVisualStudioAbstraction().XamlIndent;

            var analyzer = isCSharp ? new CSharpAnalyzer(DefaultTestLogger.Create(), indent) as IDocumentAnalyzer
                                    : new VisualBasicAnalyzer(DefaultTestLogger.Create(), indent);

            var actual = analyzer.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos, profileOverload);

            this.AssertOutput(expected, actual);
        }
        public void SingleNameContainsIsIdentified()
        {
            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), 4, this.testProfile);
            var result = cpb.GetPropertyOutput("int", "number1", isReadOnly: false);

            Assert.AreEqual(ReadWriteNumberIntOutput, result);
        }
示例#29
0
        private void ParseWithoutError(string filePath, ProjectType projType)
        {
            var result = new RapidXamlDocument();

            var text = File.ReadAllText(filePath);

            var snapshot = new FakeTextSnapshot();
            var vsa      = new TestVisualStudioAbstraction();
            var logger   = DefaultTestLogger.Create();

            try
            {
                XamlElementExtractor.Parse(
                    Path.GetFileName(filePath),
                    snapshot,
                    text,
                    RapidXamlDocument.GetAllProcessors(projType, string.Empty, vsa, logger),
                    result.Tags,
                    null,
                    RapidXamlDocument.GetEveryElementProcessor(projType, null, vsa),
                    logger);
            }
            catch (Exception exc)
            {
                Assert.Fail($"Parsing failed for '{filePath}'{Environment.NewLine}{exc}");
            }
        }
示例#30
0
        public void ReadOnlyPropertiesMatchNotReadOnlyRatherThanFallback()
        {
            var readonlyProfile = new Profile
            {
                Name           = "readonlyProfile",
                ProjectType    = ProjectType.Uwp,
                ClassGrouping  = "Grid",
                FallbackOutput = "<Fallback />",
                Mappings       = new ObservableCollection <Mapping>
                {
                    new Mapping
                    {
                        Type         = StringPropertyName,
                        NameContains = "",
                        Output       = "<ReadAndWrite />",
                        IfReadOnly   = false,
                    },
                },
            };

            var cpb    = new CodeParserBase(DefaultTestLogger.Create(), readonlyProfile.ProjectType, 4, readonlyProfile);
            var result = cpb.GetPropertyOutput(StringPropertyName, "MyProperty", isReadOnly: true);

            Assert.AreEqual("<ReadAndWrite />", result);
        }