public void TryEditStartupForNewContext_Adds_Context_Registration_To_ConfigureServices(string beforeStartupResource, string afterStartupResource, string dbContextResource)
        {
            string resourcePrefix = "compiler/resources/";

            var beforeStartupText = ResourceUtilities.GetEmbeddedResourceFileContent(resourcePrefix + beforeStartupResource);
            var afterStartupText  = ResourceUtilities.GetEmbeddedResourceFileContent(resourcePrefix + afterStartupResource);
            var dbContextText     = ResourceUtilities.GetEmbeddedResourceFileContent(resourcePrefix + dbContextResource);

            var startupTree = CSharpSyntaxTree.ParseText(beforeStartupText);
            var contextTree = CSharpSyntaxTree.ParseText(dbContextText);
            var efReference = MetadataReference.CreateFromFile(typeof(DbContext).Assembly.Location);

            var compilation = CSharpCompilation.Create("DoesNotMatter", new[] { startupTree, contextTree }, new[] { efReference });

            DbContextEditorServices testObj = new DbContextEditorServices(
                new Mock <ILibraryManager>().Object,
                new Mock <IApplicationEnvironment>().Object,
                new Mock <IFilesLocator>().Object,
                new Mock <ITemplating>().Object);

            var types       = RoslynUtilities.GetDirectTypesInCompilation(compilation);
            var startupType = ModelType.FromITypeSymbol(types.Where(ts => ts.Name == "Startup").First());
            var contextType = ModelType.FromITypeSymbol(types.Where(ts => ts.Name == "MyContext").First());

            var result = testObj.EditStartupForNewContext(startupType, "MyContext", "ContextNamespace", "MyContext-NewGuid");

            Assert.True(result.Edited);
            Assert.Equal(afterStartupText, result.NewTree.GetText().ToString());
        }
Esempio n. 2
0
        private void ValidateCommandLine(IdentityGeneratorCommandLineModel model)
        {
            var errorStrings = new List <string>();

            if (!string.IsNullOrEmpty(model.UserClass) && !RoslynUtilities.IsValidNamespace(model.UserClass))
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidUserClassName, model.UserClass));
            }

            if (!string.IsNullOrEmpty(model.DbContext) && !RoslynUtilities.IsValidNamespace(model.DbContext))
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidDbContextClassName, model.DbContext));
            }

            if (!string.IsNullOrEmpty(model.RootNamespace) && !RoslynUtilities.IsValidNamespace(model.RootNamespace))
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidNamespaceName, model.RootNamespace));
            }

            if (!string.IsNullOrEmpty(model.Layout) && model.GenerateLayout)
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidOptionCombination, "--layout", "--generateLayout"));
            }

            if (!string.IsNullOrEmpty(model.BootstrapVersion) && !IdentityGenerator.ValidBootstrapVersions.Contains(model.BootstrapVersion))
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidBootstrapVersionForScaffolding, model.BootstrapVersion, string.Join(", ", IdentityGenerator.ValidBootstrapVersions)));
            }

            if (errorStrings.Any())
            {
                throw new ArgumentException(string.Join(Environment.NewLine, errorStrings));
            }
        }
Esempio n. 3
0
        public async void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection <ITextBuffer> subjectBuffers)
        {
            if (RoslynUtilities.IsRoslynInstalled(ServiceProvider) || !LanguageUtilities.IsRunning())
            {
                return;
            }

            if (!subjectBuffers.Any(b => b.ContentType.IsOfType("CSharp")))
            {
                return;
            }

            // VS2010 only creates TextViewAdapters later; wait for it to exist.
            await Dispatcher.Yield();

            var textViewAdapter = EditorAdaptersFactoryService.GetViewAdapter(textView);

            if (textViewAdapter == null)
            {
                return;
            }
            ITextDocument document;

            if (!TextDocumentFactoryService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out document))
            {
                return;
            }

            textView.Properties.GetOrCreateSingletonProperty(() => new GoToDefinitionInterceptor(ReferenceProviders, ServiceProvider, textViewAdapter, textView, document));
        }
Esempio n. 4
0
        public async Task CSharpMetadataTest()
        {
            // Hop on to the UI thread so the language service APIs work
            await Application.Current.Dispatcher.NextFrame(DispatcherPriority.ApplicationIdle);

            // Use a type that is not in the public reference source
            textView.Caret.MoveTo(textView.FindSpan("System.IO.Log.LogStore").End);
            GetCurrentNativeTextView().Execute(VSConstants.VSStd97CmdID.GotoDefn);

            var           metadataTextView = GetCurentTextView();
            var           docService       = componentModel.GetService <ITextDocumentFactoryService>();
            ITextDocument document;

            Assert.IsTrue(docService.TryGetTextDocument(metadataTextView.TextDataModel.DocumentBuffer, out document));
            ISymbolResolver resolver = null;

            if (RoslynUtilities.IsRoslynInstalled(VsIdeTestHostContext.ServiceProvider))
            {
                resolver = new RoslynSymbolResolver();
            }
            else if (DTE.Version == "12.0")
            {
                resolver = new CSharp12Resolver();
            }
            if (resolver == null)
            {
                var symbol = resolver.GetSymbolAt(document.FilePath, metadataTextView.FindSpan("public LogStore(SafeFileHandle").End);
                Assert.IsFalse(symbol.HasLocalSource);
                Assert.AreEqual("mscorlib", symbol.AssemblyName);
                Assert.AreEqual("T:Microsoft.Win32.SafeHandles.SafeFileHandle", symbol.IndexId);
            }
        }
Esempio n. 5
0
        public async Task GeneratesEnableModuleAttributesForAllModules()
        {
            StringBuilder builder = new();

            foreach (DurianModule module in ModuleIdentity.GetAllModules().AsEnums())
            {
                builder
                .Append("[assembly: Durian.Generator.EnableModule(Durian.Info.")
                .Append(nameof(DurianModule))
                .Append('.')
                .Append(module.ToString())
                .AppendLine(")]");
            }

            CSharpSyntaxTree expected = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(builder.ToString());

            CSharpCompilation      compilation = RoslynUtilities.CreateBaseCompilation();
            DisabledModuleAnalyzer analyzer    = new();
            await analyzer.RunAnalyzer(compilation);

            SingletonGeneratorTestResult result = GeneratorTest.RunGenerator("", analyzer);

            Assert.True(result.IsGenerated);
            Assert.NotNull(result.SyntaxTree);
            Assert.True(result.SyntaxTree !.IsEquivalentTo(expected));
        }
Esempio n. 6
0
        private static MemberDeclarationSyntax CreateValidDeclaration()
        {
            CSharpSyntaxTree        tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText("class Test { }");
            MemberDeclarationSyntax decl = RoslynUtilities.ParseNode <ClassDeclarationSyntax>(tree) !;

            return(decl);
        }
        public void AddModelToContext_Adds_Model_From_Same_Project_To_Context(string beforeContextResource, string modelResource, string afterContextResource)
        {
            string resourcePrefix = "compiler/resources/";

            var beforeDbContextText = ResourceUtilities.GetEmbeddedResourceFileContent(resourcePrefix + beforeContextResource);
            var modelText           = ResourceUtilities.GetEmbeddedResourceFileContent(resourcePrefix + modelResource);
            var afterDbContextText  = ResourceUtilities.GetEmbeddedResourceFileContent(resourcePrefix + afterContextResource);

            var contextTree = CSharpSyntaxTree.ParseText(beforeDbContextText);
            var modelTree   = CSharpSyntaxTree.ParseText(modelText);
            var efReference = MetadataReference.CreateFromFile(typeof(DbContext).Assembly.Location);

            var compilation = CSharpCompilation.Create("DoesNotMatter", new[] { contextTree, modelTree }, new[] { efReference });

            DbContextEditorServices testObj = new DbContextEditorServices(
                new Mock <ILibraryManager>().Object,
                new Mock <IApplicationEnvironment>().Object,
                new Mock <IFilesLocator>().Object,
                new Mock <ITemplating>().Object);

            var types       = RoslynUtilities.GetDirectTypesInCompilation(compilation);
            var modelType   = ModelType.FromITypeSymbol(types.Where(ts => ts.Name == "MyModel").First());
            var contextType = ModelType.FromITypeSymbol(types.Where(ts => ts.Name == "MyContext").First());

            var result = testObj.AddModelToContext(contextType, modelType);

            Assert.True(result.Edited);
            Assert.Equal(afterDbContextText, result.NewTree.GetText().ToString());
        }
Esempio n. 8
0
        public async Task Succcess_When_ReferencesDurianCore()
        {
            CSharpCompilation           compilation = RoslynUtilities.CreateBaseCompilation();
            DependencyAnalyzer          analyzer    = new();
            ImmutableArray <Diagnostic> diagnostics = await analyzer.RunAnalyzer(compilation);

            Assert.Empty(diagnostics);
        }
Esempio n. 9
0
        public async Task ModulesAreEnabledByDefault()
        {
            CSharpCompilation      compilation = RoslynUtilities.CreateBaseCompilation();
            DisabledModuleAnalyzer analyzer    = new();
            await analyzer.RunAnalyzer(compilation);

            Assert.True(ModuleIdentity.GetAllModules().AsEnums().All(module => DisabledModuleAnalyzer.IsEnabled(module)));
        }
Esempio n. 10
0
        public async Task CSharpRoslynResolverTest()
        {
            if (!RoslynUtilities.IsRoslynInstalled(VsIdeTestHostContext.ServiceProvider))
            {
                Assert.Inconclusive("Roslyn is not installed");
            }

            await TestCSharpResolver(new RoslynSymbolResolver());
        }
Esempio n. 11
0
        public async Task CSharp10ResolverTest()
        {
            if (RoslynUtilities.IsRoslynInstalled(VsIdeTestHostContext.ServiceProvider))
            {
                Assert.Inconclusive("Cannot test native language services with Roslyn installed?");
            }

            await TestCSharpResolver(new CSharp10Resolver(DTE));
        }
Esempio n. 12
0
        public async Task DisablesModule_When_HasDisableModuleAttribute()
        {
            string            input       = "[assembly: Durian.DisableModule(Durian.Info.DurianModule.DefaultParam)]";
            CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation();

            compilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(input));
            DisabledModuleAnalyzer analyzer = new();
            await analyzer.RunAnalyzer(compilation);

            Assert.False(DisabledModuleAnalyzer.IsEnabled(DurianModule.DefaultParam));
        }
Esempio n. 13
0
 protected void ValidateNameSpaceName(CommandLineGeneratorModel generatorModel)
 {
     if (!string.IsNullOrEmpty(generatorModel.ControllerNamespace) &&
         !RoslynUtilities.IsValidNamespace(generatorModel.ControllerNamespace))
     {
         throw new InvalidOperationException(string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 MessageStrings.InvalidNamespaceName,
                                                 generatorModel.ControllerNamespace));
     }
 }
Esempio n. 14
0
        private string GetDefaultDbContextName()
        {
            var defaultDbContextName = $"{_applicationInfo.ApplicationName}IdentityDbContext";

            if (!RoslynUtilities.IsValidIdentifier(defaultDbContextName))
            {
                defaultDbContextName = "IdentityDataContext";
            }

            return(defaultDbContextName);
        }
Esempio n. 15
0
        public async Task CSharp12ResolverTest()
        {
            if (DTE.Version != "12.0")
            {
                Assert.Inconclusive("CSharp12Resolver only works in VS 2013");
            }
            if (RoslynUtilities.IsRoslynInstalled(VsIdeTestHostContext.ServiceProvider))
            {
                Assert.Inconclusive("Cannot test native language services with Roslyn installed?");
            }

            await TestCSharpResolver(new CSharp12Resolver());
        }
Esempio n. 16
0
        public async Task Error_When_ReferencesMainDurianPackageAndAnyDurianAnalyzerPackage()
        {
            CSharpCompilation compilation  = RoslynUtilities.CreateBaseCompilation();
            string            dir          = Path.GetDirectoryName(typeof(DependencyTests).Assembly.Location) !;
            string            mainPath     = Path.Combine(dir, "Durian.dll");
            string            analyzerPath = Path.Combine(dir, "Durian.Core.Analyzer.dll");

            compilation = compilation.AddReferences(MetadataReference.CreateFromFile(mainPath), MetadataReference.CreateFromFile(analyzerPath));

            DependencyAnalyzer analyzer = new();

            Assert.True(await analyzer.ProducesDiagnostic(compilation, DurianDiagnostics.DUR0007_DoNotReferencePackageIfManagerIsPresent));
        }
Esempio n. 17
0
        public async Task Success_When_ReferencesMainPackage()
        {
            CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation();
            string            dir         = Path.GetDirectoryName(typeof(DependencyTests).Assembly.Location) !;
            string            mainPath    = Path.Combine(dir, "Durian.dll");

            compilation = compilation.AddReferences(MetadataReference.CreateFromFile(mainPath));

            DependencyAnalyzer          analyzer    = new();
            ImmutableArray <Diagnostic> diagnostics = await analyzer.RunAnalyzer(compilation);

            Assert.Empty(diagnostics);
        }
Esempio n. 18
0
        public async Task Warning_When_HasMultipleAnalyzerPackages_And_NoManager()
        {
            CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation();
            string            dir         = Path.GetDirectoryName(typeof(DependencyTests).Assembly.Location) !;

            compilation = compilation.AddReferences(
                MetadataReference.CreateFromFile(Path.Combine(dir, "Durian.Core.Analyzer.dll")),
                MetadataReference.CreateFromFile(Path.Combine(dir, "Durian.InterfaceTargets.dll"))
                );

            DependencyAnalyzer analyzer = new();

            Assert.True(await analyzer.ProducesDiagnostic(compilation, DurianDiagnostics.DUR0008_MultipleAnalyzers));
        }
Esempio n. 19
0
        public static void PrepareSolution(TestContext context)
        {
            DTE.Solution.Open(Path.Combine(SolutionDir, "TestBed.sln"));

            componentModel = (IComponentModel)VsIdeTestHostContext.ServiceProvider.GetService(typeof(SComponentModel));
            fileName       = Path.GetFullPath(Path.Combine(SolutionDir, "Basic", "File.vb"));
            DTE.ItemOperations.OpenFile(fileName).Activate();
            textView = GetCurentTextView();

            isRoslyn = RoslynUtilities.IsRoslynInstalled(VsIdeTestHostContext.ServiceProvider);
            if (isRoslyn)
            {
                resolver = new RoslynSymbolResolver();
            }
            else
            {
                resolver = new VBResolver();
            }
        }
Esempio n. 20
0
        private void ValidateCommandLine(IdentityGeneratorCommandLineModel model)
        {
            var errorStrings = new List <string>();;

            if (!string.IsNullOrEmpty(model.UserClass) && !RoslynUtilities.IsValidIdentifier(model.UserClass))
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidUserClassName, model.UserClass));;
            }

            if (!string.IsNullOrEmpty(model.DbContext) && !RoslynUtilities.IsValidNamespace(model.DbContext))
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidDbContextClassName, model.DbContext));;
            }

            if (!string.IsNullOrEmpty(model.RootNamespace) && !RoslynUtilities.IsValidNamespace(model.RootNamespace))
            {
                errorStrings.Add(string.Format(MessageStrings.InvalidNamespaceName, model.RootNamespace));
            }

            if (errorStrings.Any())
            {
                throw new ArgumentException(string.Join(Environment.NewLine, errorStrings));
            }
        }
Esempio n. 21
0
        public void AddAccessor(ButlerAccessorType accessorType, ButlerAccessibility accessibility)
        {
            if (accessorType == ButlerAccessorType.Set && !_definedAccessors.Contains(ButlerAccessorType.Get))
            {
                throw new Exception("Cannot define a set accessor without a get accessor.");
            }

            AccessorDeclarationSyntax accessor = SyntaxFactory.AccessorDeclaration(RoslynUtilities.FromAccessorType(accessorType));

            accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));

            if (accessibility > _accessibility)
            {
                throw new Exception($"The accessibility modifier of the {accessorType.ToString ()} accessor must be more restrictive than the property");
            }

            if (accessibility != _accessibility)
            {
                accessor = accessor.AddModifiers(SyntaxFactory.Token(RoslynUtilities.FromAccessibility(accessibility)));
            }

            Info = Info.AddAccessorListAccessors(accessor);
            _definedAccessors.Add(accessorType);
        }
Esempio n. 22
0
        public async Task Error_When_IsVisualBasic()
        {
            VisualBasicCompilation      compilation = VisualBasicCompilation.Create(RoslynUtilities.DefaultCompilationName, null, RoslynUtilities.GetBaseReferences());
            IsCSharpCompilationAnalyzer analyzer    = new();

            Assert.True(await analyzer.ProducesDiagnostic(compilation, DurianDiagnostics.DUR0004_DurianModulesAreValidOnlyInCSharp));
        }
Esempio n. 23
0
        public async Task Success_When_IsCSharp()
        {
            CSharpCompilation           compilation = CSharpCompilation.Create(RoslynUtilities.DefaultCompilationName, null, RoslynUtilities.GetBaseReferences());
            IsCSharpCompilationAnalyzer analyzer    = new();
            ImmutableArray <Diagnostic> diagnostics = await analyzer.RunAnalyzer(compilation);

            Assert.Empty(diagnostics);
        }
Esempio n. 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CompilationFixture"/> class.
 /// </summary>
 public CompilationFixture()
 {
     Compilation = RoslynUtilities.CreateBaseCompilation();
 }
Esempio n. 25
0
 public void HasErrorsReturnsFalseByDefault()
 {
     Data.CompilationData data = new(RoslynUtilities.CreateBaseCompilation());
     Assert.False(data.HasErrors);
 }
Esempio n. 26
0
 public void CompilationIsNotNullAfterConstructor()
 {
     Data.CompilationData data = new(RoslynUtilities.CreateBaseCompilation());
     Assert.True(data.Compilation is not null);
 }
 public void TestCreateValidNameSpace(string identifier, bool expectedValue)
 {
     Assert.Equal(expectedValue, RoslynUtilities.IsValidNamespace(identifier));
 }
 public void TestCreateEscapedIdentifier(string identifier, string expectedValue)
 {
     Assert.Equal(expectedValue, RoslynUtilities.CreateEscapedIdentifier(identifier));
 }
Esempio n. 29
0
 public void SetAccessibility(ButlerAccessibility accessibility)
 {
     _accessibility = accessibility;
     Info           = Info.AddModifiers(SyntaxFactory.Token(RoslynUtilities.FromAccessibility(accessibility)));
 }