Ejemplo n.º 1
0
        public void UpdateConfigForSqlDbFileUpgrade_updates_and_saves_config()
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(
                "<configuration>" +
                "  <connectionStrings>" +
                "    <add connectionString=\"Data source=.\\SQLExpress;AttachDbFilename=C:\\MyFolder\\MyDataFile.mdf;Database=dbname;Trusted_Connection=Yes;\" />" +
                "  </connectionStrings>" +
                "</configuration>");

            var mockConfigFileUtils =
                new Mock <ConfigFileUtils>(Mock.Of <Project>(), Mock.Of <IServiceProvider>(), null, Mock.Of <IVsUtils>(), null);

            mockConfigFileUtils
            .Setup(u => u.LoadConfig())
            .Returns(xmlDoc);

            EdmUtils.UpdateConfigForSqlDbFileUpgrade(
                mockConfigFileUtils.Object,
                Mock.Of <Project>(),
                Mock.Of <IVsUpgradeLogger>());

            mockConfigFileUtils.Verify(u => u.SaveConfig(It.IsAny <XmlDocument>()), Times.Once());
        }
Ejemplo n.º 2
0
        public void SafeLoadXmlFromString_can_load_xml_without_entities()
        {
            var xmlDoc = EdmUtils.SafeLoadXmlFromString("<entity-framework />");

            Assert.NotNull(xmlDoc);
            Assert.Equal("entity-framework", xmlDoc.DocumentElement.Name);
        }
Ejemplo n.º 3
0
        public void GetEntityFrameworkVersion_returns_version_when_ef_installed()
        {
            var helper = new MockDTE(
                ".NETFramework,Version=v4.5", references: new[] { MockDTE.CreateReference("EntityFramework", "6.0.0.0") });

            var schemaVersion = EdmUtils.GetEntityFrameworkVersion(helper.Project, helper.ServiceProvider);

            Assert.Equal(EntityFrameworkVersion.Version3, schemaVersion);
        }
Ejemplo n.º 4
0
        public void IsDataServicesEdmx_returns_false_for_no_data_services_edmx()
        {
            Assert.False(
                EdmUtils.IsDataServicesEdmx(XDocument.Parse("<Edmx xmlns=\"abc\"><DataServices /></Edmx>")));

            Assert.False(
                EdmUtils.IsDataServicesEdmx(
                    XDocument.Parse("<Edmx xmlns=\"http://schemas.microsoft.com/ado/2009/11/edmx\" />")));
        }
Ejemplo n.º 5
0
        public void GetEntityFrameworkVersion_returns_null_when_misc_files()
        {
            var project         = MockDTE.CreateMiscFilesProject();
            var serviceProvider = new Mock <IServiceProvider>();

            var schemaVersion = EdmUtils.GetEntityFrameworkVersion(project, serviceProvider.Object);

            Assert.Null(schemaVersion);
        }
Ejemplo n.º 6
0
 public void IsValidModelNamespace_returns_false_for_invalid_namespaces()
 {
     // the version does not matter since the definition
     // of allowed strings for namespaces have not changed since v1
     Assert.False(EdmUtils.IsValidModelNamespace(null));
     Assert.False(EdmUtils.IsValidModelNamespace(string.Empty));
     Assert.False(EdmUtils.IsValidModelNamespace("\u0001\u0002"));
     Assert.False(EdmUtils.IsValidModelNamespace("<>"));
 }
Ejemplo n.º 7
0
        public void ConstructValidModelNamespace_returns_sanitized_proposed_namespace_if_sanitized_proposed_namespace_valid()
        {
            Assert.Equal(
                "proposed",
                EdmUtils.ConstructValidModelNamespace("<proposed>", "default"));

            Assert.Equal(
                "proposed",
                EdmUtils.ConstructValidModelNamespace("<123_proposed>", "default"));
        }
Ejemplo n.º 8
0
        public void ConstructValidModelNamespace_returns_default_namespace_if_proposed_namespace_null_or_empty_string()
        {
            Assert.Equal(
                "default",
                EdmUtils.ConstructValidModelNamespace(null, "default"));

            Assert.Equal(
                "default",
                EdmUtils.ConstructValidModelNamespace(string.Empty, "default"));
        }
Ejemplo n.º 9
0
        public void SafeLoadXmlFromString_throws_if_xml_contains_entities()
        {
            var message = Assert.Throws <XmlException>(
                () => EdmUtils.SafeLoadXmlFromString(
                    "<!ENTITY network \"network\">\n<entity-framework>&network;</entity-framework>")).Message;

            Assert.Contains("DTD", message);
            Assert.Contains("DtdProcessing", message);
            Assert.Contains("Parse", message);
        }
Ejemplo n.º 10
0
        public void SafeLoadXmlFromPath_can_load_xml_without_entities()
        {
            var filePath = Path.GetTempFileName();

            File.WriteAllText(filePath, "<entity-framework />");

            var xmlDoc = EdmUtils.SafeLoadXmlFromPath(filePath);

            Assert.NotNull(xmlDoc);
            Assert.Equal("entity-framework", xmlDoc.DocumentElement.Name);
        }
Ejemplo n.º 11
0
        public void UpdateConfigForSqlDbFileUpgrade_does_not_save_config_if_content_not_loaded()
        {
            var mockConfigFileUtils = new Mock <ConfigFileUtils>(
                Mock.Of <Project>(), Mock.Of <IServiceProvider>(), null, Mock.Of <IVsUtils>(), null);

            EdmUtils.UpdateConfigForSqlDbFileUpgrade(
                mockConfigFileUtils.Object,
                Mock.Of <Project>(),
                Mock.Of <IVsUpgradeLogger>());

            mockConfigFileUtils.Verify(u => u.SaveConfig(It.IsAny <XmlDocument>()), Times.Never());
        }
Ejemplo n.º 12
0
        public void IsDataServicesEdmx_returns_true_for_known_data_services_edmx()
        {
            const string edmxTemplate = "<Edmx xmlns=\"{0}\"><DataServices /></Edmx>";

            foreach (var edmxNs in SchemaManager.GetEDMXNamespaceNames())
            {
                Assert.True(
                    EdmUtils.IsDataServicesEdmx(
                        XDocument.Parse(
                            string.Format(edmxTemplate, edmxNs))));
            }
        }
Ejemplo n.º 13
0
        public void SafeLoadXmlFromPath_throws_if_xml_contains_entities()
        {
            var filePath = Path.GetTempFileName();

            File.WriteAllText(filePath, "<!ENTITY network \"network\">\n<entity-framework>&network;</entity-framework>");

            var message = Assert.Throws <XmlException>(
                () => EdmUtils.SafeLoadXmlFromPath(filePath)).Message;

            Assert.Contains("DTD", message);
            Assert.Contains("DtdProcessing", message);
            Assert.Contains("Parse", message);
        }
Ejemplo n.º 14
0
        // <summary>
        //     Project retargeting event handler.
        //     1. Check the project type, return immediately if project is misc project or a project that does not support EF.
        //     2. Find all the EDMX files in the project. Skip Data Services edmx files and linked files.
        //     3. Sync all the namespaces based on the new target framework
        // </summary>
        public void RetargetFilesInProject()
        {
            var project = VSHelpers.GetProject(_hierarchy);

            if (project == null ||
                !VsUtils.EntityFrameworkSupportedInProject(project, _serviceProvider, allowMiscProject: false))
            {
                return;
            }

            var targetSchemaVersion = EdmUtils.GetEntityFrameworkVersion(project, _serviceProvider, useLatestIfNoEF: false);

            Debug.Assert(targetSchemaVersion != null, "schema version must not be null for projects that support EF");

            var documentMap = new Dictionary <string, object>();

            foreach (var vsFileInfo in GetEdmxFileInfos())
            {
                try
                {
                    var projectItem = VsUtils.GetProjectItem(_hierarchy, vsFileInfo.ItemId);

                    // skip the process for astoria edmx file or a linked edmx file
                    if (IsDataServicesEdmx(projectItem.get_FileNames(1)) ||
                        VsUtils.IsLinkProjectItem(projectItem))
                    {
                        continue;
                    }

                    var doc = RetargetFile(vsFileInfo.Path, targetSchemaVersion);
                    if (doc != null)
                    {
                        documentMap.Add(vsFileInfo.Path, doc);
                    }
                }
                catch (Exception ex)
                {
                    // TODO: When there is an exception; should we continue?
                    VsUtils.LogStandardError(
                        string.Format(CultureInfo.CurrentCulture, Resources.ErrorSynchingEdmxNamespaces, vsFileInfo.Path, ex.Message),
                        vsFileInfo.Path, 0, 0);
                    throw;
                }
            }

            WriteModifiedFiles(project, documentMap);
        }
Ejemplo n.º 15
0
        public void GetEntityFrameworkVersion_returns_latest_version_when_EF_dll_in_the_project_and_useLatestIfNoEf_true()
        {
            var netFxToSchemaVersionMapping =
                new[]
            {
                new KeyValuePair <string, Version>(".NETFramework,Version=v4.5", new Version(3, 0, 0, 0)),
                new KeyValuePair <string, Version>(".NETFramework,Version=v4.0", new Version(3, 0, 0, 0)),
                new KeyValuePair <string, Version>(".NETFramework,Version=v3.5", new Version(1, 0, 0, 0))
            };

            foreach (var mapping in netFxToSchemaVersionMapping)
            {
                var helper        = new MockDTE(/* .NET Framework Moniker */ mapping.Key, references: new Reference[0]);
                var schemaVersion = EdmUtils.GetEntityFrameworkVersion(helper.Project, helper.ServiceProvider, useLatestIfNoEF: true);
                Assert.Equal(/*expected schema version */ mapping.Value, schemaVersion);
            }
        }
Ejemplo n.º 16
0
        public void ConstructValidModelNamespace_returns_default_namespace_if_sanitized_proposed_namespace_invalid_or_empty_string()
        {
            Assert.Equal(
                "default",
                EdmUtils.ConstructValidModelNamespace("&", "default"));

            Assert.Equal(
                "default",
                EdmUtils.ConstructValidModelNamespace("&\u0001", "default"));

            Assert.Equal(
                "default",
                EdmUtils.ConstructValidModelNamespace("&123", "default"));

            Assert.Equal(
                "default",
                EdmUtils.ConstructValidModelNamespace("_a a", "default"));
        }
Ejemplo n.º 17
0
        public void UpdateConfigForSqlDbFileUpgrade_logs_exceptions()
        {
            var mockConfigFileUtils = new Mock <ConfigFileUtils>(
                Mock.Of <Project>(), Mock.Of <IServiceProvider>(), null, Mock.Of <IVsUtils>(), null);

            mockConfigFileUtils
            .Setup(u => u.LoadConfig())
            .Throws(new InvalidOperationException("Loading Failed"));

            var mockLogger = new Mock <IVsUpgradeLogger>();

            EdmUtils.UpdateConfigForSqlDbFileUpgrade(
                mockConfigFileUtils.Object,
                Mock.Of <Project>(),
                mockLogger.Object);

            var expectedErrorMessage =
                string.Format(Resources.ErrorDuringSqlDatabaseFileUpgrade, null, "Loading Failed");

            mockLogger
            .Verify(l => l.LogMessage(2, It.IsAny <string>(), It.IsAny <string>(), expectedErrorMessage), Times.Once());
        }
Ejemplo n.º 18
0
        public void CreateUpdateCodeGenStrategyCommand_returns_null_when_attempting_to_update_CodeGenStrategy_to_same_value()
        {
            var modelManager             = new Mock <ModelManager>(null, null).Object;
            var modelProvider            = new Mock <XmlModelProvider>().Object;
            var entityDesignArtifactMock =
                new Mock <EntityDesignArtifact>(modelManager, new Uri("urn:dummy"), modelProvider);

            using (var designerInfoRoot = new EFDesignerInfoRoot(entityDesignArtifactMock.Object, new XElement("_")))
            {
                const string designerPropertyName = "CodeGenerationStrategy";
                designerInfoRoot
                .AddDesignerInfo(
                    "Options",
                    SetupOptionsDesignerInfo(designerPropertyName, "None"));

                entityDesignArtifactMock
                .Setup(a => a.DesignerInfo)
                .Returns(designerInfoRoot);

                Assert.Null(EdmUtils.SetCodeGenStrategyToNoneCommand(entityDesignArtifactMock.Object));
            }
        }
Ejemplo n.º 19
0
        CreateUpdateCodeGenStrategyCommand_returns_UpdateDefaultableValueCommand_when_updating_CodeGenStrategy_value_from_empty_string()
        {
            var modelManager             = new Mock <ModelManager>(null, null).Object;
            var modelProvider            = new Mock <XmlModelProvider>().Object;
            var entityDesignArtifactMock =
                new Mock <EntityDesignArtifact>(modelManager, new Uri("urn:dummy"), modelProvider);

            using (var designerInfoRoot = new EFDesignerInfoRoot(entityDesignArtifactMock.Object, new XElement("_")))
            {
                const string designerPropertyName = "CodeGenerationStrategy";
                designerInfoRoot
                .AddDesignerInfo(
                    "Options",
                    SetupOptionsDesignerInfo(designerPropertyName, string.Empty));

                entityDesignArtifactMock
                .Setup(a => a.DesignerInfo)
                .Returns(designerInfoRoot);

                Assert.IsType <UpdateDefaultableValueCommand <string> >(
                    EdmUtils.SetCodeGenStrategyToNoneCommand(entityDesignArtifactMock.Object));
            }
        }
Ejemplo n.º 20
0
 public void IsDataServicesEdmx_returns_false_for_invalid_or_non_existing_path()
 {
     Assert.False(EdmUtils.IsDataServicesEdmx((string)null));
     Assert.False(EdmUtils.IsDataServicesEdmx(string.Empty));
     Assert.False(EdmUtils.IsDataServicesEdmx(Guid.NewGuid().ToString()));
 }
Ejemplo n.º 21
0
 public void IsValidModelNamespace_returns_true_for_valid_namespaces()
 {
     // the version does not matter since the definition
     // of allowed strings for namespaces have not changed since v1
     Assert.True(EdmUtils.IsValidModelNamespace("abc"));
 }
Ejemplo n.º 22
0
 public void ConstructUniqueNamespaces_returns_proposed_namespace_if_existing_namespaces_null()
 {
     Assert.Equal("testNamespace", EdmUtils.ConstructUniqueNamespace("testNamespace", null));
 }
Ejemplo n.º 23
0
 public void ConstructUniqueNamespaces_returns_uniquified_namespace_()
 {
     Assert.Equal("Model1", EdmUtils.ConstructUniqueNamespace("Model", new HashSet <string> {
         "Model"
     }));
 }
Ejemplo n.º 24
0
        // protected virtual to allow mocking
        protected virtual bool IsDataServicesEdmx(string filePath)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(filePath), "Invalid filePath");

            return(EdmUtils.IsDataServicesEdmx(filePath));
        }
Ejemplo n.º 25
0
 public void IsDataServicesEdmx_returns_false_for_invalid_Xml_file()
 {
     Assert.False(EdmUtils.IsDataServicesEdmx(GetType().Assembly.Location));
 }
Ejemplo n.º 26
0
        internal static void SqlCeUpgradeService_OnUpgradeProject(IVsHierarchy hierarchy, IVsUpgradeLogger logger)
        {
            if (PackageManager.Package != null &&
                PackageManager.Package.ModelManager != null)
            {
                // since this is about retargeting EDMX files on disk, no need to process other file extensions from any converters
                var fileFinder = new VSFileFinder(EntityDesignArtifact.ExtensionEdmx);
                fileFinder.FindInProject(hierarchy);

                var project = VSHelpers.GetProject(hierarchy);

                // skip the step if it is a miscellaneous project.
                if (project != null &&
                    !VsUtils.IsMiscellaneousProject(project))
                {
                    IDictionary <string, object> documentMap = new Dictionary <string, object>();
                    foreach (var vsFileInfo in fileFinder.MatchingFiles)
                    {
                        try
                        {
                            var projectItem = VsUtils.GetProjectItem(hierarchy, vsFileInfo.ItemId);

                            // Dev 10 bug 648969: skip the process for astoria edmx file.
                            if (EdmUtils.IsDataServicesEdmx(projectItem.get_FileNames(1)))
                            {
                                continue;
                            }

                            // Check whether project item is a linked item
                            var isLinkItem = VsUtils.IsLinkProjectItem(projectItem);

                            if (!isLinkItem)
                            {
                                var doc = MetadataConverterDriver.SqlCeInstance.Convert(SafeLoadXmlFromPath(vsFileInfo.Path));
                                if (doc != null)
                                {
                                    documentMap.Add(vsFileInfo.Path, doc);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var errMsg = String.Format(
                                CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, vsFileInfo.Path, ex.Message);
                            logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, vsFileInfo.Path, errMsg);
                            return;
                        }
                    }

                    if (documentMap.Count > 0)
                    {
                        VsUtils.WriteCheckoutXmlFilesInProject(documentMap);
                    }

                    // now update the config file as needed
                    var configFileUtils = new ConfigFileUtils(project, PackageManager.Package);
                    try
                    {
                        var configXmlDoc = configFileUtils.LoadConfig();
                        if (configXmlDoc != null) // check config file exists
                        {
                            if (ConnectionManager.UpdateSqlCeProviderInConnectionStrings(configXmlDoc))
                            {
                                configFileUtils.SaveConfig(configXmlDoc);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var errMsg = String.Format(
                            CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, configFileUtils.GetConfigPath(), ex.Message);
                        logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg);
                    }
                }
            }
        }
Ejemplo n.º 27
0
        // protected virtual to allow mocking
        protected virtual XmlDocument SafeLoadXmlFromPath(string filePath)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(filePath), "Invalid filePath");

            return(EdmUtils.SafeLoadXmlFromPath(filePath, preserveWhitespace: true));
        }