Esempio n. 1
0
        public void Create_creates_valid_EntityConnection_and_returns_EF_version()
        {
            var mockProviderServices = SetupMockProviderServices();

            mockProviderServices
            .Protected()
            .Setup <DbProviderManifest>("GetDbProviderManifest", ItExpr.IsAny <string>())
            .Returns(SqlProviderServices.Instance.GetProviderManifest("2008"));

            var mockResolver = SetupMockResolver(mockProviderServices);

            foreach (var targetEFVersion in EntityFrameworkVersion.GetAllVersions())
            {
                Version actualEFVersion;

                var entityConnection =
                    new StoreSchemaConnectionFactory().Create(
                        mockResolver.Object,
                        "System.Data.SqlClient",
                        "Server=test",
                        targetEFVersion,
                        out actualEFVersion);

                Assert.NotNull(entityConnection);
                var expectedVersion =
                    targetEFVersion == EntityFrameworkVersion.Version2
                        ? EntityFrameworkVersion.Version1
                        : targetEFVersion;

                Assert.Equal(expectedVersion, actualEFVersion);
            }
        }
Esempio n. 2
0
 public void CsdlVersion_was_added_if_EntityFramework_version_was_added()
 {
     // +1 to account for CSDL version 1.1
     Assert.Equal(
         EntityFrameworkVersion.GetAllVersions().Count() + 1,
         CsdlVersion.GetAllVersions().Count());
 }
Esempio n. 3
0
 public void GetInitialModelContents_returns_contents()
 {
     foreach (var targetSchemaVersion in EntityFrameworkVersion.GetAllVersions())
     {
         Assert.Equal(
             EdmUtils.CreateEdmxString(targetSchemaVersion, string.Empty, string.Empty, string.Empty),
             new InitialModelContentsFactory().GetInitialModelContents(targetSchemaVersion));
     }
 }
 public void FunctionImportColumnInformation_always_enabled()
 {
     foreach (var targetSchemaVersion in EntityFrameworkVersion.GetAllVersions())
     {
         Assert.Equal(
             FeatureState.VisibleAndEnabled,
             IsFeatureEnabledForArtifact(
                 targetSchemaVersion,
                 EdmFeatureManager.GetFunctionImportColumnInformationFeatureState));
     }
 }
Esempio n. 5
0
        internal static HashSet <string> InitializeExistingNamespaces(Project project)
        {
            var existingNamespaces = new HashSet <string>();

            if (project != null)
            {
                // find the namespace used in the CSDL section of each existing edmx file in the project
                var vsHierarchy = VsUtils.GetVsHierarchy(project, Services.ServiceProvider);
                var fileFinder  = new VSFileFinder(EntityDesignArtifact.ExtensionEdmx);
                fileFinder.FindInProject(vsHierarchy);

                foreach (var fileInfo in fileFinder.MatchingFiles)
                {
                    try
                    {
                        var xmlDocument = EdmUtils.SafeLoadXmlFromPath(fileInfo.Path);
                        foreach (var schemaVersion in EntityFrameworkVersion.GetAllVersions())
                        {
                            var nsMgr = SchemaManager.GetEdmxNamespaceManager(xmlDocument.NameTable, schemaVersion);

                            foreach (
                                XmlElement e in xmlDocument.SelectNodes("/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/csdl:Schema", nsMgr))
                            {
                                var namespaceValue = e.GetAttribute("Namespace");
                                if (!string.IsNullOrEmpty(namespaceValue))
                                {
                                    existingNamespaces.Add(namespaceValue);
                                }
                            }
                        }
                    }
                    // swallow various exceptions that come from reading the file or parsing xml
                    // We just skip this document in the event of an exception.
                    catch (IOException)
                    {
                    }
                    catch (UnauthorizedAccessException)
                    {
                    }
                    catch (NotSupportedException)
                    {
                    }
                    catch (SecurityException)
                    {
                    }
                    catch (XmlException)
                    {
                    }
                }
            }
            return(existingNamespaces);
        }
Esempio n. 6
0
 public void CopyToSSDL_false_causes_CopyExtendedPropertiesToSsdlElement_to_not_copy_property()
 {
     foreach (var version in EntityFrameworkVersion.GetAllVersions())
     {
         var csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL = CreateEntityTypeWithExtendedProperty(
             SchemaManager.GetEDMXNamespaceName(EntityFrameworkVersion.Version1), "false");
         var ssdlEntityTypeElement = new XElement(
             (XNamespace)(SchemaManager.GetSSDLNamespaceName(EntityFrameworkVersion.Version1)) + "EntityType",
             new XAttribute("Name", "TestEntityType"));
         OutputGeneratorHelpers.CopyExtendedPropertiesToSsdlElement(
             csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL, ssdlEntityTypeElement);
         Assert.Empty(ssdlEntityTypeElement.Elements());
     }
 }
Esempio n. 7
0
        public void GetAllPrimitiveTypes_returns_all_primitive_types_for_version()
        {
            foreach (var schemaVersion in EntityFrameworkVersion.GetAllVersions())
            {
                // remove geo spatial types for schema versions V1 and V2
                var expectedTypes =
                    PrimitiveType
                    .GetEdmPrimitiveTypes()
                    .Where(t => schemaVersion == EntityFrameworkVersion.Version3 || !IsGeoSpatialType(t))
                    .Select(t => t.Name);

                Assert.Equal(expectedTypes, ModelHelper.AllPrimitiveTypes(schemaVersion));
            }
        }
Esempio n. 8
0
        public void LoadFunctionReturnTableDetails_not_invoked_for_pre_V3_target_schema()
        {
            var mockEntityConnection = new Mock <EntityConnection>();

            foreach (var version in EntityFrameworkVersion.GetAllVersions())
            {
                var mockLoader =
                    new Mock <EntityStoreSchemaGeneratorDatabaseSchemaLoader>(
                        mockEntityConnection.Object, version)
                {
                    CallBase = true
                };

                mockLoader.Setup(l => l.LoadTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()))
                .Returns(Enumerable.Empty <TableDetailsRow>());

                mockLoader.Setup(l => l.LoadViewDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()))
                .Returns(Enumerable.Empty <TableDetailsRow>());

                mockLoader.Setup(l => l.LoadRelationships(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()))
                .Returns(Enumerable.Empty <RelationshipDetailsRow>());

                mockLoader.Setup(l => l.LoadFunctionDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()))
                .Returns(Enumerable.Empty <FunctionDetailsRowView>());

                mockLoader.Setup(
                    l => l.LoadFunctionReturnTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()))
                .Returns(Enumerable.Empty <TableDetailsRow>());

                mockLoader.Object.LoadStoreSchemaDetails(new List <EntityStoreSchemaFilterEntry>());

                mockLoader.Verify(
                    l => l.LoadTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()), Times.Once());

                mockLoader.Verify(
                    l => l.LoadViewDetails(It.IsAny <IList <EntityStoreSchemaFilterEntry> >()), Times.Once());

                mockLoader.Verify(
                    l => l.LoadRelationships(It.IsAny <IList <EntityStoreSchemaFilterEntry> >()), Times.Once());

                mockLoader.Verify(
                    l => l.LoadFunctionDetails(It.IsAny <IList <EntityStoreSchemaFilterEntry> >()), Times.Once());

                mockLoader.Verify(
                    l => l.LoadFunctionReturnTableDetails(It.IsAny <IEnumerable <EntityStoreSchemaFilterEntry> >()),
                    version == EntityFrameworkVersion.Version3 ? Times.Once() : Times.Never());
            }
        }
Esempio n. 9
0
 public void CopyToSSDL_true_causes_CopyExtendedPropertiesToSsdlElement_to_copy_property()
 {
     foreach (var version in EntityFrameworkVersion.GetAllVersions())
     {
         var csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL = CreateEntityTypeWithExtendedProperty(
             SchemaManager.GetEDMXNamespaceName(version), "true");
         var ssdlEntityTypeElement = new XElement(
             (XNamespace)(SchemaManager.GetSSDLNamespaceName(version)) + "EntityType",
             new XAttribute("Name", "TestEntityType"));
         OutputGeneratorHelpers.CopyExtendedPropertiesToSsdlElement(
             csdlEntityTypeWithVersionedEdmxNamespaceCopyToSSDL, ssdlEntityTypeElement);
         Assert.Equal(
             "<MyProp p1:MyAttribute=\"MyValue\" xmlns:p1=\"http://myExtendedProperties\" xmlns=\"http://myExtendedProperties\" />",
             ssdlEntityTypeElement.Elements().First().ToString());
     }
 }
        /// <summary>
        ///     Creates an EntityConnection loaded with the providers metadata for the latest available store schema.
        ///     Note that the targetEntityFrameworkVersion parameter uses internal EntityFramework version numbers as
        ///     described in the <see cref="EntityFrameworkVersion" /> class.
        /// </summary>
        /// <param name="resolver">Resolver used to resolve provider services.</param>
        /// <param name="providerInvariantName">The provider invariant name.</param>
        /// <param name="connectionString">The connection for the providers connection.</param>
        /// <param name="maxAllowedSchemaVersion">The maximum allowed Entity Framework schema version that is being targeted.</param>
        /// <param name="storeSchemaModelVersion">
        ///     The version of the store schema model supported by the provider. Can be either v1 or v3 (store schema model in v2 did not change
        ///     from v1, in v3 TVFs are supported and the provider needs to know how to handle Esql queries that ask for TVFs).
        ///     Note that schema view artifacts themselves are v1 since there is nothing that is needed to ask for v3 concepts that
        ///     cannot be expressed in v1 terms.
        ///     **This value MUST NOT be used as the version of the model that will be created for the user (which can be
        ///     any version regardless of this value), nor as the version of schema view artifacts (which is always v1)
        ///     but rather it is a version of concepts we are asking the provider to return details for (to put it simply if this is v3
        ///     we will ask the provider about TVFs, otherwise this is v1 and we don't ask about TVFs)**
        /// </param>
        /// <returns>An EntityConnection that can query the ConceptualSchemaDefinition for the provider.</returns>
        /// <remarks>virtual for testing</remarks>
        public virtual EntityConnection Create(
            IDbDependencyResolver resolver, string providerInvariantName, string connectionString,
            Version maxAllowedSchemaVersion, out Version storeSchemaModelVersion)
        {
            Debug.Assert(resolver != null, "resolver != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "providerInvarianName cannot be null or empty");
            Debug.Assert(!string.IsNullOrWhiteSpace(connectionString), "connectionString cannot be null or empty");
            Debug.Assert(EntityFrameworkVersion.IsValidVersion(maxAllowedSchemaVersion), "invalid maxAllowedSchemaVersion");

            // We are going to try loading all versions of the store schema model starting from the newest.
            // The first version of the model that was shipped with EntityFrameworkVersions.Version1 and EntityFrameworkVersions.Version2 is the last one
            // we try, if it fails to load let the exception to propagate up to the caller.
            var versions =
                EntityFrameworkVersion
                .GetAllVersions()
                .Where(v => v > EntityFrameworkVersion.Version2 && v <= maxAllowedSchemaVersion)
                .OrderByDescending(v => v);

            foreach (var version in versions)
            {
                try
                {
                    storeSchemaModelVersion = version;
                    return
                        (Create(
                             resolver,
                             providerInvariantName,
                             connectionString,
                             storeSchemaModelVersion));
                }
                catch (Exception e)
                {
                    // Ignore the exception with the current version and try the next one.
                    if (!IsCatchableExceptionType(e))
                    {
                        throw;
                    }
                }
            }
            storeSchemaModelVersion = EntityFrameworkVersion.Version1;
            return(Create(resolver, providerInvariantName, connectionString, storeSchemaModelVersion));
        }
        protected internal override bool ExpectEFObjectForXObject(XObject xobject)
        {
            var xe = xobject as XElement;

            if (xe != null)
            {
                foreach (var n in SchemaManager.GetEDMXNamespaceNames())
                {
                    // see if this element is the "Edmx" element.  We don't exepct a EFObject for this element
                    if (xe.Name.NamespaceName.Equals(n, StringComparison.OrdinalIgnoreCase))
                    {
                        if (xe.Name.LocalName.Equals("Edmx", StringComparison.OrdinalIgnoreCase))
                        {
                            return(false);
                        }
                    }
                }

                // now look for items that are in the EF set of namespaces (ie, csdl/ssdl/msl/edmx namespaces.
                // If something isn't in this namespace, we return false below (since it won't have a model element)
                // if something is in this namespace, we'll base this to the base class, which will return true.
                //
                // the reason this is here is there will be asserts after undo/redo operations if we can't find
                // a model element for the xnode that is part of the undo/redo.  Returning false from this method
                // tells us not to expect the model element.
                //
                foreach (var v in EntityFrameworkVersion.GetAllVersions())
                {
                    foreach (var s in SchemaManager.GetAllNamespacesForVersion(v))
                    {
                        if (xe.Name.NamespaceName.Equals(s, StringComparison.OrdinalIgnoreCase))
                        {
                            // we only expect EFObjects for items in the Entity Framework namespaces
                            return(base.ExpectEFObjectForXObject(xobject));
                        }
                    }
                }
            }

            return(false);
        }
        public void RetargetWithMetadataConverter_does_not_modify_xml_if_converter_returns_null()
        {
            foreach (var schemaVersion in EntityFrameworkVersion.GetAllVersions())
            {
                var model = new XDocument(new XElement("root"));
                model.Changed +=
                    (sender, args) => { throw new InvalidOperationException("Unexpected changes to model."); };

                var mockConverter = new Mock <MetadataConverterDriver>();
                mockConverter
                .Setup(c => c.Convert(It.IsAny <XmlDocument>(), It.IsAny <Version>()))
                .Returns(
                    (XmlDocument doc, Version version) =>
                {
                    Assert.Same(schemaVersion, version);
                    return(null);
                });

                RetargetXmlNamespaceCommand.RetargetWithMetadataConverter(model, schemaVersion, mockConverter.Object);
            }
        }
Esempio n. 13
0
        private bool VerifyUserEdit(XName xn)
        {
            if (_namespaces == null)
            {
                _namespaces = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                foreach (var v in EntityFrameworkVersion.GetAllVersions())
                {
                    foreach (var s in SchemaManager.GetAllNamespacesForVersion(v))
                    {
                        _namespaces.Add(s);
                    }
                }
            }

            if (_namespaces.Contains(xn.NamespaceName))
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
        public void ToLegacyMetadataWorkspace_creates_equivalent_legacy_MetadataWorkspace_for_all_versions()
        {
            const string ssdlTemplate =
                @"<Schema Namespace=""NorthwindEF5Model.Store"" Provider=""System.Data.SqlClient"" ProviderManifestToken=""2008"" Alias=""Self"" xmlns=""{0}"" xmlns:store=""http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"">"
                +
                @"  <EntityType Name=""Customers"">" +
                @"    <Key>" +
                @"      <PropertyRef Name=""CustomerID"" />" +
                @"    </Key>" +
                @"    <Property Name=""CustomerID"" Type=""nchar"" MaxLength=""5"" Nullable=""false"" />" +
                @"    <Property Name=""CompanyName"" Type=""nvarchar"" MaxLength=""40"" Nullable=""false"" />" +
                @"  </EntityType>" +
                @"  <EntityContainer Name=""Container"" />" +
                @"</Schema>";

            const string csdlTemplate =
                @"<Schema xmlns=""{0}"" Namespace=""dummy"">" +
                @"    <EntityContainer Name=""DummyContainer""/>" +
                @"</Schema>";

            const string mslTemplate =
                @"<Mapping Space=""C-S"" xmlns=""{0}"">" +
                @"  <EntityContainerMapping StorageEntityContainer=""Container"" CdmEntityContainer=""DummyContainer"" />" +
                @"</Mapping>";

            foreach (var version in EntityFrameworkVersion.GetAllVersions())
            {
                var storeItemCollection =
                    Utils.CreateStoreItemCollection(
                        string.Format(
                            ssdlTemplate,
                            SchemaManager.GetSSDLNamespaceName(version)));
                var edmItemCollection =
                    new EdmItemCollection(
                        new[]
                {
                    XmlReader.Create(
                        new StringReader(
                            string.Format(
                                csdlTemplate,
                                SchemaManager.GetCSDLNamespaceName(version))))
                });
                var mappingItemCollection =
                    new StorageMappingItemCollection(
                        edmItemCollection,
                        storeItemCollection,
                        new[]
                {
                    XmlReader.Create(
                        new StringReader(
                            string.Format(
                                mslTemplate,
                                SchemaManager.GetMSLNamespaceName(version))))
                });
                var workspace = new MetadataWorkspace(
                    () => edmItemCollection,
                    () => storeItemCollection,
                    () => mappingItemCollection);

                var legacyWorkspace = workspace.ToLegacyMetadataWorkspace();

                Assert.NotNull(legacyWorkspace);

                var legacyStoreItemCollection = legacyWorkspace.GetItemCollection(LegacyMetadata.DataSpace.SSpace);

                Assert.Equal(
                    storeItemCollection.GetItems <GlobalItem>().Count,
                    legacyStoreItemCollection.GetItems <LegacyMetadata.GlobalItem>().Count);

                Assert.NotNull(
                    legacyStoreItemCollection.GetItem <LegacyMetadata.EntityType>("NorthwindEF5Model.Store.Customers"));

                var legacyEdmItemCollection =
                    (LegacyMetadata.EdmItemCollection)legacyWorkspace.GetItemCollection(LegacyMetadata.DataSpace.CSpace);
                Assert.NotNull(legacyEdmItemCollection);
                Assert.Equal(version, EntityFrameworkVersion.DoubleToVersion(legacyEdmItemCollection.EdmVersion));

                Assert.NotNull(legacyWorkspace.GetItemCollection(LegacyMetadata.DataSpace.CSSpace));
            }
        }