Beispiel #1
0
        public void RunStarted_uses_context_class_name_if_SaveConnectionStringInAppConfig_false()
        {
            var mockCodeGenerator = new Mock <CodeFirstModelGenerator>(MockDTE.CreateProject());

            mockCodeGenerator
            .Setup(g => g.Generate(It.IsAny <DbModel>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(new[] { new KeyValuePair <string, string>() });

            var modelBuilderSettings =
                new ModelBuilderSettings {
                SaveConnectionStringInAppConfig = false, AppConfigConnectionPropertyName = "ConnString"
            };

            var replacementsDictionary =
                new Dictionary <string, string>
            {
                { "$safeitemname$", "MyContext" },
                { "$rootnamespace$", "Project.Data" }
            };

            new OneEFWizard(vsUtils: Mock.Of <IVsUtils>())
            .RunStarted(modelBuilderSettings, mockCodeGenerator.Object, replacementsDictionary);

            mockCodeGenerator.Verify(g => g.Generate(It.IsAny <DbModel>(), "Project.Data", "MyContext", "MyContext"), Times.Once());
        }
Beispiel #2
0
        public void RunStarted_saves_context_generated_code_replacementsDictionary_as_contextfilecontents()
        {
            var mockCodeGenerator = new Mock <CodeFirstModelGenerator>(MockDTE.CreateProject());

            mockCodeGenerator
            .Setup(g => g.Generate(It.IsAny <DbModel>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(new[] { new KeyValuePair <string, string>("MyContext", "context code") });

            var modelBuilderSettings =
                new ModelBuilderSettings {
                SaveConnectionStringInAppConfig = true, AppConfigConnectionPropertyName = "ConnString"
            };

            var replacementsDictionary =
                new Dictionary <string, string>
            {
                { "$safeitemname$", "MyContext" },
                { "$rootnamespace$", "Project.Data" }
            };

            new OneEFWizard(vsUtils: Mock.Of <IVsUtils>())
            .RunStarted(modelBuilderSettings, mockCodeGenerator.Object, replacementsDictionary);

            Assert.Equal("context code", replacementsDictionary["$contextfilecontents$"]);
        }
Beispiel #3
0
        // Test stopped working with 15.6 Preview 7 - plan to re-enable with https://github.com/aspnet/EntityFramework6/issues/541
        // [Fact]
        public void Generate_throws_when_error_in_entity_type_template()
        {
            var project = MockDTE.CreateProject();
            var token   = Guid.NewGuid().ToString();

            using (AddCustomizedTemplates(project))
            {
                var templatePath = Path.GetTempFileName();
                try
                {
                    File.WriteAllText(templatePath, "<# throw new Exception(\"" + token + "\"); #>");

                    var fullPathProperty = project.ProjectItems.Item("CodeTemplates").ProjectItems
                                           .Item("EFModelFromDatabase").ProjectItems.Item("EntityType.cs.t4").Properties.Cast <Property>()
                                           .First(i => i.Name == "FullPath");
                    Mock.Get(fullPathProperty).SetupGet(p => p.Value).Returns(templatePath);

                    var generator = new CodeFirstModelGenerator(project);

                    var ex = Assert.Throws <CodeFirstModelGenerationException>(
                        () => generator.Generate(Model, "WebApplication1.Models", "MyContext", "MyContextConnString")
                        .ToArray());

                    Assert.Equal(
                        string.Format(Resources.ErrorGeneratingCodeFirstModel, "Entity.cs"),
                        ex.Message);
                    Assert.Contains(token, ex.InnerException.Message);
                }
                finally
                {
                    File.Delete(templatePath);
                }
            }
        }
Beispiel #4
0
        public void RunStarted_creates_valid_context_name_if_safeitemname_is_not_valid_identifier()
        {
            var mockVsUtils = new Mock <IVsUtils>();
            var wizard      = new OneEFWizard(vsUtils: mockVsUtils.Object);

            var mockCodeGenerator = new Mock <CodeFirstModelGenerator>(MockDTE.CreateProject());

            mockCodeGenerator
            .Setup(g => g.Generate(It.IsAny <DbModel>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(new[] { new KeyValuePair <string, string>(string.Empty, string.Empty) });

            var settings = new ModelBuilderSettings {
                VSApplicationType = VisualStudioProjectSystem.WebApplication
            };
            var replacenentsDictionary = new Dictionary <string, string>
            {
                { "$safeitemname$", "3My.Con text" },
                { "$rootnamespace$", "Project" }
            };

            wizard.RunStarted(settings, mockCodeGenerator.Object, replacenentsDictionary);

            mockCodeGenerator.Verify(
                g => g.Generate(
                    It.IsAny <DbModel>(),
                    "Project",
                    /*contextClassName*/ "_3MyContext",
                    /*connectionStringName*/ "_3MyContext"),
                Times.Once());
        }
        public void GetProjectTargetFileName_returns_name()
        {
            var project = MockDTE.CreateProject(
                properties: new Dictionary <string, object> {
                { "OutputFileName", "ConsoleApplication1.exe" }
            });

            Assert.Equal("ConsoleApplication1.exe", VsUtils.GetProjectTargetFileName(project));
        }
        public void GetProjectTargetFileName_returns_null_when_nonstring()
        {
            var project = MockDTE.CreateProject(
                properties: new Dictionary <string, object> {
                { "OutputFileName", 42 }
            });

            Assert.Null(VsUtils.GetProjectTargetFileName(project));
        }
Beispiel #7
0
        public void Generate_returns_code_when_vb()
        {
            var generator = new CodeFirstModelGenerator(MockDTE.CreateProject(kind: MockDTE.VBProjectKind));

            var files = generator.Generate(Model, "WebApplication1.Models", "MyContext", "MyContextConnString").ToArray();

            Assert.Equal(2, files.Length);
            Assert.Equal(new[] { "MyContext.vb", "Entity.vb" }, files.Select(p => p.Key));
        }
Beispiel #8
0
        public void Generate_returns_code_when_vb_and_empty_model()
        {
            var generator = new CodeFirstModelGenerator(MockDTE.CreateProject(kind: MockDTE.VBProjectKind));

            var files = generator.Generate(null, "WebApplication1.Models", "MyContext", "MyContextConnString").ToArray();

            Assert.Equal(1, files.Length);
            Assert.Equal("MyContext.vb", files[0].Key);
            Assert.Contains(Resources.CodeFirstCodeFile_DbSetComment_VB, files[0].Value);
        }
        public void GetInstalledEntityFrameworkAssemblyVersion_returns_EF_version_when_EF_and_SDE()
        {
            var project = MockDTE.CreateProject(
                new[]
            {
                MockDTE.CreateReference("System.Data.Entity", "4.0.0.0"),
                MockDTE.CreateReference("EntityFramework", "5.0.0.0")
            });

            Assert.Equal(RuntimeVersion.Version5Net45, VsUtils.GetInstalledEntityFrameworkAssemblyVersion(project));
        }
Beispiel #10
0
        public void GetProjectRoot_returns_fullpath_when_csharp_project()
        {
            const string fullPath = @"C:\Path\To\Project\";
            var          project  = MockDTE.CreateProject(
                properties: new Dictionary <string, object> {
                { "FullPath", fullPath }
            });

            var root = VsUtils.GetProjectRoot(project, Mock.Of <IServiceProvider>());

            Assert.Equal(fullPath, root.FullName);
        }
        public static ModelBuilderWizardForm CreateWizard(ModelGenerationOption generationOption = (ModelGenerationOption)(-1),
                                                          Project project = null, string modelPath = null, IServiceProvider serviceProvider = null)
        {
            var modelBuilderSettings =
                new ModelBuilderSettings
            {
                Project          = project ?? MockDTE.CreateProject(),
                GenerationOption = generationOption,
                ModelPath        = modelPath
            };

            return(CreateWizard(modelBuilderSettings, serviceProvider));
        }
Beispiel #12
0
        public void GetProjectTargetDir_returns_dir_when_csharp_project()
        {
            var project = MockDTE.CreateProject(
                properties: new Dictionary <string, object> {
                { "FullPath", @"C:\Path\To\Project\" }
            },
                configurationProperties: new Dictionary <string, object> {
                { "OutputPath", @"bin\Debug\" }
            });

            var targetDir = VsUtils.GetProjectTargetDir(project, Mock.Of <IServiceProvider>());

            Assert.Equal(@"C:\Path\To\Project\bin\Debug\", targetDir);
        }
Beispiel #13
0
        // Test stopped working with 15.6 Preview 7 - plan to re-enable with https://github.com/aspnet/EntityFramework6/issues/541
        // [Fact]
        public void Generate_returns_code_when_cs_and_customized()
        {
            var project = MockDTE.CreateProject();

            using (AddCustomizedTemplates(project))
            {
                var generator = new CodeFirstModelGenerator(project);

                var files = generator.Generate(Model, "WebApplication1.Models", "MyContext", "MyContextConnString").ToArray();

                Assert.Equal(2, files.Length);
                Assert.Equal(new[] { "MyContext.cs", "Entity.cs" }, files.Select(p => p.Key));
                Assert.True(files.All(p => p.Value == "Customized"));
            }
        }
Beispiel #14
0
        public void GetProjectReferenceAssemblyNames_returns_references()
        {
            var project = MockDTE.CreateProject(
                new[]
            {
                MockDTE.CreateReference("System.Data.Entity", "4.0.0.0"),
                MockDTE.CreateReference("EntityFramework", "5.0.0.0")
            });

            var referenceAssemblyNames = VsUtils.GetProjectReferenceAssemblyNames(project).ToArray();

            Assert.Equal(2, referenceAssemblyNames.Count());
            Assert.Equal("EntityFramework", referenceAssemblyNames.Last().Key);
            Assert.Equal(new Version(5, 0, 0, 0), referenceAssemblyNames.Last().Value);
        }
Beispiel #15
0
        public void AddProjectReference_adds_reference()
        {
            var vsReferences = new Mock <References>();
            var vsProject    = new Mock <VSProject2>();

            vsProject.SetupGet(p => p.References).Returns(vsReferences.Object);

            var project = MockDTE.CreateProject();

            Mock.Get(project).Setup(p => p.Object).Returns(vsProject.Object);

            VsUtils.AddProjectReference(project, "System.Data");

            vsReferences.Verify(r => r.Add("System.Data"));
        }
Beispiel #16
0
        private static void Run_OnDeactivate_creates_and_verifies_model_path(
            ModelGenerationOption generationOption, LangEnum language, bool isWebSite, string expectedExtension)
        {
            var mockDte =
                new MockDTE(
                    ".NETFramework, Version=v4.5",
                    isWebSite
                        ? MockDTE.CreateWebSite(
                        properties: new Dictionary <string, object>
            {
                { "CurrentWebsiteLanguage", language == LangEnum.CSharp ? "C#" : "VB" }
            },
                        assemblyReferences: new AssemblyReference[0])
                        : MockDTE.CreateProject(
                        kind: language == LangEnum.CSharp ? MockDTE.CSharpProjectKind : MockDTE.VBProjectKind,
                        assemblyReferences: new Reference[0]));

            var modelBuilderSettings = new ModelBuilderSettings
            {
                NewItemFolder    = @"C:\temp",
                ModelName        = "myModel",
                Project          = mockDte.Project,
                GenerationOption = generationOption
            };

            var mockWizardPageStart =
                new Mock <WizardPageStart>(ModelBuilderWizardFormHelper.CreateWizard(modelBuilderSettings, mockDte.ServiceProvider), null)
            {
                CallBase = true
            };

            mockWizardPageStart
            .Protected()
            .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>())
            .Returns(false);

            mockWizardPageStart.Object.OnDeactivate();

            mockWizardPageStart
            .Protected()
            .Verify("VerifyModelFilePath", Times.Once(), @"C:\temp\myModel" + expectedExtension);
        }
        public void AssemblyLoader_passed_non_WebsiteProject_can_find_correct_paths_to_DLLs()
        {
            const string vsInstallPath = @"C:\My\Test\VS\InstallPath";
            const string projectPath   = @"C:\My\Test\ProjectPath";
            var          project       =
                MockDTE.CreateProject(
                    new[]
            {
                MockDTE.CreateReference3(
                    "EntityFramework", "6.0.0.0", "EntityFramework",
                    Path.Combine(projectPath, "EntityFramework.dll")),
                MockDTE.CreateReference3(
                    "EntityFramework.SqlServer", "6.0.0.0", "EntityFramework.SqlServer",
                    Path.Combine(projectPath, "EntityFramework.SqlServer.dll")),
                MockDTE.CreateReference3(
                    "EntityFramework.SqlServerCompact", "6.0.0.0",
                    "EntityFramework.SqlServerCompact",
                    Path.Combine(projectPath, "EntityFramework.SqlServerCompact.dll")),
                MockDTE.CreateReference3(
                    "My.Project.Reference", "6.0.0.0", "My.Project.Reference",
                    Path.Combine(projectPath, "My.Project.Reference.dll"), true)
            });
            var assemblyLoader = new DatabaseGenerationAssemblyLoader(project, vsInstallPath);

            // assert that the DLLs installed under VS are resolved there
            Assert.Equal(
                Path.Combine(vsInstallPath, "EntityFramework.dll"),
                assemblyLoader.GetAssemblyPath("EntityFramework"));
            Assert.Equal(
                Path.Combine(vsInstallPath, "EntityFramework.SqlServer.dll"),
                assemblyLoader.GetAssemblyPath("EntityFramework.SqlServer"));
            Assert.Equal(
                Path.Combine(vsInstallPath, "EntityFramework.SqlServerCompact.dll"),
                assemblyLoader.GetAssemblyPath("EntityFramework.SqlServerCompact"));

            // assert that other project references are resolved to wherever their reference points to
            Assert.Equal(
                Path.Combine(projectPath, "My.Project.Reference.dll"),
                assemblyLoader.GetAssemblyPath("My.Project.Reference"));
        }
Beispiel #18
0
        public void RunStarted_handles_CodeFirstModelGenerationException_and_shows_error_dialog()
        {
            var project           = MockDTE.CreateProject();
            var mockCodeGenerator = new Mock <CodeFirstModelGenerator>(project);

            var innerException = new Exception("InnerException", new InvalidOperationException("nested InnerException"));

            mockCodeGenerator
            .Setup(g => g.Generate(It.IsAny <DbModel>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Throws(new CodeFirstModelGenerationException("Failed generating code.", innerException));

            var mockVsUtils = new Mock <IVsUtils>();

            var replacementsDictionary = new Dictionary <string, string>
            {
                { "$safeitemname$", "context.cs" },
                { "$rootnamespace$", "My.Namespace" }
            };

            new OneEFWizard(vsUtils: mockVsUtils.Object)
            .RunStarted(new ModelBuilderSettings(), mockCodeGenerator.Object, replacementsDictionary);

            mockVsUtils.Verify(u => u.ShowErrorDialog("Failed generating code.\r\n" + innerException), Times.Once());
        }
Beispiel #19
0
        public void GetInstalledEntityFrameworkAssemblyVersion_returns_null_when_none()
        {
            var project = MockDTE.CreateProject(Enumerable.Empty <Reference>());

            Assert.Null(VsUtils.GetInstalledEntityFrameworkAssemblyVersion(project));
        }
Beispiel #20
0
        public void GetInstalledEntityFrameworkAssemblyVersion_returns_version_when_only_SDE()
        {
            var project = MockDTE.CreateProject(new[] { MockDTE.CreateReference("System.Data.Entity", "4.0.0.0") });

            Assert.Equal(new Version(4, 0, 0, 0), VsUtils.GetInstalledEntityFrameworkAssemblyVersion(project));
        }
Beispiel #21
0
        public void GetInstalledEntityFrameworkAssemblyVersion_returns_version_when_only_EF()
        {
            var project = MockDTE.CreateProject(new[] { MockDTE.CreateReference("EntityFramework", "6.0.0.0") });

            Assert.Equal(RuntimeVersion.Version6, VsUtils.GetInstalledEntityFrameworkAssemblyVersion(project));
        }
Beispiel #22
0
 public void IsMiscellaneousProject_detects_misc_files_project()
 {
     Assert.True(VsUtils.IsMiscellaneousProject(MockDTE.CreateMiscFilesProject()));
     Assert.False(VsUtils.IsMiscellaneousProject(MockDTE.CreateProject()));
 }
Beispiel #23
0
        public void GetProjectKind_when_csharp()
        {
            var project = MockDTE.CreateProject(kind: MockDTE.CSharpProjectKind);

            Assert.Equal(VsUtils.ProjectKind.CSharp, VsUtils.GetProjectKind(project));
        }
Beispiel #24
0
        public void GetProjectKind_when_vb()
        {
            var project = MockDTE.CreateProject(kind: MockDTE.VBProjectKind);

            Assert.Equal(VsUtils.ProjectKind.VB, VsUtils.GetProjectKind(project));
        }
Beispiel #25
0
        public void GetProjectKind_when_unknown()
        {
            var project = MockDTE.CreateProject(kind: null);

            Assert.Equal(VsUtils.ProjectKind.Unknown, VsUtils.GetProjectKind(project));
        }
Beispiel #26
0
 public void IsWebSiteProject_when_not_web()
 {
     Assert.False(VsUtils.IsWebSiteProject(MockDTE.CreateProject()));
 }