Example #1
0
        public void TemplateSupported_returns_false_for_NetFramework3_5()
        {
            var mockMonikerHelper =
                new MockDTE(".NETFramework,Version=v3.5");

            Assert.False(
                DbContextCodeGenerator.TemplateSupported(
                    mockMonikerHelper.Project,
                    mockMonikerHelper.ServiceProvider));
        }
 public void FindDbContextTemplate_finds_the_EF5_CSharp_template_when_targeting_dotNET4_with_CSharp()
 {
     UITestRunner.Execute(TestContext.TestName, 
         () =>
             {
                 var proj = CreateProject("DbContextCSharpNet40", "4", "CSharp");
                 var dbCtxGenerator = new DbContextCodeGenerator();
                 var ctxTemplate = dbCtxGenerator.FindDbContextTemplate(proj);
                 Assert.IsTrue(ctxTemplate.EndsWith(@"DbCtxCSEF5\DbContext_CS_V5.0.vstemplate"));
             });
 }
Example #3
0
        public void TemplateSupported_returns_false_for_Misc_project()
        {
            const string vsMiscFilesProjectUniqueName = "<MiscFiles>";

            var mockMonikerHelper =
                new MockDTE(".NETFramework,Version=v4.0", vsMiscFilesProjectUniqueName);

            Assert.False(
                DbContextCodeGenerator.TemplateSupported(
                    mockMonikerHelper.Project,
                    mockMonikerHelper.ServiceProvider));
        }
Example #4
0
        public void TemplateSupported_returns_true_when_targeting_NetFramework4_or_newer()
        {
            var targets =
                new[]
            {
                ".NETFramework,Version=v4.0",
                ".NETFramework,Version=v4.5",
                ".NETFramework,Version=v4.5.1"
            };

            foreach (var target in targets)
            {
                var mockMonikerHelper = new MockDTE(target);

                Assert.True(
                    DbContextCodeGenerator.TemplateSupported(
                        mockMonikerHelper.Project,
                        mockMonikerHelper.ServiceProvider));
            }
        }
Example #5
0
        public void TemplateSupported_returns_false_when_for_non_NetFramework_projects()
        {
            var targets =
                new[]
            {
                ".NETFramework,Version=v1.1",
                "XBox,Version=v4.0",
                "abc",
                string.Empty,
                null
            };

            foreach (var target in targets)
            {
                var mockMonikerHelper = new MockDTE(target);

                Assert.False(
                    DbContextCodeGenerator.TemplateSupported(
                        mockMonikerHelper.Project,
                        mockMonikerHelper.ServiceProvider));
            }
        }
        public void RunFinished()
        {
            if (_edmxItem == null)
            {
                if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.EmptyModelCodeFirst ||
                    _modelBuilderSettings.GenerationOption == ModelGenerationOption.CodeFirstFromDatabase)
                {
                    Debug.Assert(
                        _modelBuilderSettings.ModelBuilderEngine == null ^
                        _modelBuilderSettings.GenerationOption == ModelGenerationOption.CodeFirstFromDatabase,
                        "Model should be null for Empty Model and not null CodeFirst from database");

                    AddCodeFirstItems();
                }

                return;
            }

            var fileExtension = Path.GetExtension(_edmxItem.FileNames[1]);

            Debug.Assert(
                _modelBuilderSettings.Project.Equals(_edmxItem.ContainingProject),
                "ActiveSolutionProject is not the EDMX file's containing project");
            using (new VsUtils.HourglassHelper())
            {
                var    package = PackageManager.Package;
                Window window  = null;

                try
                {
                    ConfigFileHelper.UpdateConfig(_modelBuilderSettings);

                    // save the model generated in the wizard UI.
                    if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                    {
                        var writingModelWatch = new Stopwatch();
                        writingModelWatch.Start();
                        var modelEdmx = ((EdmxModelBuilderEngine)_modelBuilderSettings.ModelBuilderEngine).Edmx;

                        if (!string.Equals(fileExtension, EntityDesignArtifact.ExtensionEdmx, StringComparison.OrdinalIgnoreCase))
                        {
                            // convert the file if this isn't EDMX
                            var edmxFileInfo      = new FileInfo(_edmxItem.FileNames[1]);
                            var conversionContext = new ModelConversionContextImpl(
                                _edmxItem.ContainingProject,
                                _edmxItem,
                                edmxFileInfo,
                                _modelBuilderSettings.TargetSchemaVersion,
                                modelEdmx);
                            VSArtifact.DispatchToConversionExtensions(
                                EscherExtensionPointManager.LoadModelConversionExtensions(),
                                fileExtension,
                                conversionContext,
                                loading: false);
                            File.WriteAllText(edmxFileInfo.FullName, conversionContext.OriginalDocument);
                        }
                        else
                        {
                            // we need to use XmlWriter to output so that XmlDeclaration is preserved.
                            using (var modelWriter = XmlWriter.Create(
                                       _edmxItem.FileNames[1],
                                       new XmlWriterSettings {
                                Indent = true
                            }))
                            {
                                modelEdmx.WriteTo(modelWriter);
                            }
                        }

                        writingModelWatch.Stop();
                        VsUtils.LogOutputWindowPaneMessage(
                            _edmxItem.ContainingProject,
                            string.Format(
                                CultureInfo.CurrentCulture,
                                Properties.Resources.WritingModelTimeMsg,
                                writingModelWatch.Elapsed));
                    }

                    // set the ItemType for the generated .edmx file
                    if (_modelBuilderSettings.VSApplicationType != VisualStudioProjectSystem.Website &&
                        string.Equals(
                            fileExtension,
                            EntityDesignArtifact.ExtensionEdmx,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        _edmxItem.Properties.Item(ItemTypePropertyName).Value = EntityDeployBuildActionName;
                    }

                    // now open created file in VS using default viewer
                    window = _edmxItem.Open(Constants.vsViewKindPrimary);
                    Debug.Assert(window != null, "Unable to get window for created edmx file");
                }
                finally
                {
                    package.ModelGenErrorCache.RemoveErrors(_edmxItem.FileNames[1]);
                }

                // Construct an editing context and make all final edits that require the file is opened.
                var edmxFileUri    = new Uri(_edmxItem.FileNames[1]);
                var designArtifact =
                    package.ModelManager.GetNewOrExistingArtifact(
                        edmxFileUri, new VSXmlModelProvider(package, package)) as EntityDesignArtifact;
                Debug.Assert(
                    designArtifact != null,
                    "artifact should be of type EntityDesignArtifact but received type " + designArtifact.GetType().FullName);
                Debug.Assert(
                    designArtifact.StorageModel != null, "designArtifact StorageModel cannot be null for Uri " + edmxFileUri.AbsolutePath);
                Debug.Assert(
                    designArtifact.ConceptualModel != null,
                    "designArtifact ConceptualModel cannot be null for Uri " + edmxFileUri.AbsolutePath);

                if (designArtifact != null &&
                    designArtifact.StorageModel != null &&
                    designArtifact.ConceptualModel != null)
                {
                    var designerSafeBeforeAddingTemplates = designArtifact.IsDesignerSafe;

                    var editingContext =
                        package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(designArtifact.Uri);
                    Debug.Assert(editingContext != null, "Null EditingContext for artifact " + edmxFileUri.AbsolutePath);
                    if (editingContext != null)
                    {
                        // Add DbContext templates when generation is GenerateFromDatabase. (connection is configured)
                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                        {
                            new DbContextCodeGenerator().AddDbContextTemplates(
                                _edmxItem,
                                _modelBuilderSettings.UseLegacyProvider);
                        }

                        // Create FunctionImports for every new Function
                        var cp = PrepareCommandsAndIntegrityChecks(_modelBuilderSettings, editingContext, designArtifact);

                        if (DbContextCodeGenerator.TemplateSupported(_edmxItem.ContainingProject, package))
                        {
                            // Add command setting CodeGenerationStrategy to "None" for EmptyModel. (connection is not yet configured)
                            // NOTE: For EmptyModel, the templates will be added after the connection is configured.
                            //       (i.e. during "Generate Database from Model" or "Refresh from Database")
                            if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.EmptyModel)
                            {
                                var cmd = EdmUtils.SetCodeGenStrategyToNoneCommand(designArtifact);
                                if (cmd != null)
                                {
                                    if (cp == null)
                                    {
                                        var cpc = new CommandProcessorContext(
                                            editingContext,
                                            EfiTransactionOriginator.CreateNewModelId,
                                            Resources.Tx_SetCodeGenerationStrategy);
                                        cp = new CommandProcessor(cpc, cmd);
                                    }
                                    else
                                    {
                                        cp.EnqueueCommand(cmd);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Templates not supported, add reference to SDE. (.NET Framework 3.5)
                            VsUtils.AddProjectReference(_edmxItem.ContainingProject, "System.Data.Entity");
                        }

                        if (cp != null)
                        {
                            cp.Invoke();
                        }

                        // save the artifact to make it look as though updates were part of creation
                        _edmxItem.Save();

                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase &&
                            !designerSafeBeforeAddingTemplates)
                        {
                            // If the artifact became safe after adding references we need to reload it (this can happen
                            // on .NET Framework 4 where we would originally create a v3 edmx if the user selected EF6 -
                            // the artifact will be flagged as invalid since there is no runtime which could handle v3
                            // but after we added references to EF6 the artifacts becomes valid and need to be reloaded).
                            designArtifact.DetermineIfArtifactIsDesignerSafe();
                            if (designArtifact.IsDesignerSafe)
                            {
                                Debug.Assert(!designArtifact.IsDirty, "Reloading dirty artifact - changes will be lost.");

                                // Since the artifact was originally not valid we did not create the diagram for it.
                                // Using ReloadDocData will cause the diagram to be recreated. Note we don't need to
                                // reload the artifact itself since it has not changed.
                                ((DocData)
                                 VSHelpers.GetDocData(package, designArtifact.Uri.LocalPath)).ReloadDocData(0);
                            }
                        }
                    }

                    if (window != null)
                    {
                        window.Activate();
                    }
                }
            }
        }
        public void FindDbContextTemplate_finds_the_EF6_VB_web_site_template()
        {
            UITestRunner.Execute(TestContext.TestName, 
                () =>
                    {
                        var project = CreateWebSiteProject("DbContextVBNet45WebEF6", "4.5", "VisualBasic");
                        var generator = new DbContextCodeGenerator();

                        var template = generator.FindDbContextTemplate(project, useLegacyTemplate: false);

                        StringAssert.EndsWith(template, @"DbCtxVBWSEF6\DbContext_VB_WS_V6.0.vstemplate");
                    });
        }
        public void FindDbContextTemplate_finds_the_EF6_CSharp_template()
        {
            UITestRunner.Execute(TestContext.TestName, 
                () =>
                    {
                        var project = CreateProject("DbContextCSharpNet45EF6", "4.5", "CSharp");
                        var generator = new DbContextCodeGenerator();

                        var template = generator.FindDbContextTemplate(project, useLegacyTemplate: false);

                        StringAssert.EndsWith(template, @"DbCtxCSEF6\DbContext_CS_V6.0.vstemplate");
                    });
        }
 public void FindDbContextTemplate_finds_the_EF5_VB_web_site_template_when_targeting_dotNET4_5_web_site_with_VB()
 {
     UITestRunner.Execute(TestContext.TestName, 
         () =>
             {
                 var proj = CreateWebSiteProject("DbContextVBNet45Web", "4.5", "VisualBasic");
                 var dbCtxGenerator = new DbContextCodeGenerator();
                 var ctxTemplate = dbCtxGenerator.FindDbContextTemplate(proj);
                 Assert.IsTrue(ctxTemplate.EndsWith(@"DbCtxVBWSEF5\DbContext_VB_WS_V5.0.vstemplate"));
             });
 }