public static IEnumerable<EntitySet> Convert(
            IList<EntitySet> sourceEntitySets,
            Version targetEntityFrameworkVersion,
            string providerInvariantName,
            string providerManifestToken,
            IDbDependencyResolver dependencyResolver)
        {
            Debug.Assert(sourceEntitySets != null, "sourceEntitySets != null");
            Debug.Assert(sourceEntitySets.All(e => e.DefiningQuery == null), "unexpected defining query");
            Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "invalid providerInvariantName");
            Debug.Assert(!string.IsNullOrWhiteSpace(providerManifestToken), "invalid providerManifestToken");
            Debug.Assert(dependencyResolver != null, "dependencyResolver != null");

            if (!sourceEntitySets.Any())
            {
                // it's empty anyways
                return sourceEntitySets;
            }

            var providerServices = dependencyResolver.GetService<DbProviderServices>(providerInvariantName);
            Debug.Assert(providerServices != null, "providerServices != null");

            var transientWorkspace =
                CreateTransientMetadataWorkspace(
                    sourceEntitySets,
                    targetEntityFrameworkVersion,
                    providerInvariantName,
                    providerManifestToken,
                    providerServices.GetProviderManifest(providerManifestToken));

            return sourceEntitySets.Select(
                e => CloneWithDefiningQuery(
                    e,
                    CreateDefiningQuery(e, transientWorkspace, providerServices)));
        }
Exemplo n.º 2
0
        public DatabaseCreator(IDbDependencyResolver resolver, MigrationsChecker migrationsChecker = null)
        {
            DebugCheck.NotNull(resolver);

            _resolver = resolver;
            _migrationsChecker = migrationsChecker ?? new MigrationsChecker();
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Call this method to add a <see cref="IDbDependencyResolver" /> instance to the Chain of
        ///     Responsibility of resolvers that are used to resolve dependencies needed by the Entity Framework.
        /// </summary>
        /// <remarks>
        ///     Resolvers are asked to resolve dependencies in reverse order from which they are added. This means
        ///     that a resolver can be added to override resolution of a dependency that would already have been
        ///     resolved in a different way.
        ///     The only exception to this is that any dependency registered in the application's config file
        ///     will always be used in preference to using a dependency resolver added here, unless the
        ///     overrideConfigFile is set to true in which case the resolver added here will also override config
        ///     file settings.
        /// </remarks>
        /// <param name="resolver"> The resolver to add. </param>
        /// <param name="overrideConfigFile">If true, then the resolver added will take precedence over settings in the config file.</param>
        public void AddDependencyResolver(IDbDependencyResolver resolver, bool overrideConfigFile)
        {
            Check.NotNull(resolver, "resolver");

            _internalConfiguration.CheckNotLocked("AddDependencyResolver");
            _internalConfiguration.AddDependencyResolver(resolver, overrideConfigFile);
        }
Exemplo n.º 4
0
        /// <summary>
        ///     Retorna em uma lista flat os resolvers agragados no resolver informado.
        /// </summary>
        private static IEnumerable <IDbDependencyResolver> GetInternalResolvers(
            this IDbDependencyResolver resolver)
        {
            if (resolver == null)
            {
                throw new ArgumentNullException(nameof(resolver));
            }

            if (IsCompositeResolver(resolver))
            {
                return(ExplodeCompositeResolver(resolver));
            }
            else if (IsResolverChain(resolver))
            {
                return(ExplodeResolverChain(resolver));
            }
            else if (IsRootDependencyResolver(resolver))
            {
                return(ExplodeRootDepencendyResolver(resolver));
            }
            else if (IsDbProviderServices(resolver))
            {
                return(ExplodeDbProviderServices(resolver));
            }
            else
            {
                return new [] { resolver }
            };
            //    throw new NotImplementedException();
        }
Exemplo n.º 5
0
 /// <summary>
 /// Calls <see cref="M:System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver.GetServices(System.Type,System.Object)" /> passing the generic type of the method and the given
 /// name as arguments.
 /// </summary>
 /// <typeparam name="T"> The contract type to resolve. </typeparam>
 /// <param name="resolver"> The resolver to use. </param>
 /// <param name="key"> The key of the dependency to resolve. </param>
 /// <returns> All resolved dependencies, or an <see cref="T:System.Collections.Generic.IEnumerable`1" /> if no services are resolved.</returns>
 public static IEnumerable <T> GetServices <T>(
     this IDbDependencyResolver resolver,
     object key)
 {
     Check.NotNull <IDbDependencyResolver>(resolver, nameof(resolver));
     return(resolver.GetServices(typeof(T), key).OfType <T>());
 }
Exemplo n.º 6
0
 public WrappingDependencyResolver(
     IDbDependencyResolver snapshot,
     Func <TService, object, TService> serviceWrapper)
 {
     this._snapshot       = snapshot;
     this._serviceWrapper = serviceWrapper;
 }
Exemplo n.º 7
0
 public OnLoaded()
 {
     _snapshot      = new Mock <IDbDependencyResolver>().Object;
     _configuration = CreateMockInternalConfiguration(null, _snapshot);
     _configuration.Setup(m => m.OnLoadedHandlers)
     .Returns(new EventHandler <DbConfigurationLoadedEventArgs>[] { Handler1, Handler2, Handler2 });
 }
Exemplo n.º 8
0
        public StoreModelBuilder(
            string providerInvariantName,
            string providerManifestToken,
            Version targetEntityFrameworkVersion,
            string namespaceName,
            IDbDependencyResolver resolver,
            bool generateForeignKeyProperties)
        {
            Debug.Assert(
                !string.IsNullOrWhiteSpace(providerInvariantName),
                "!string.IsNullOrWhiteSpace(providerInvariantName");
            Debug.Assert(
                !string.IsNullOrWhiteSpace(providerManifestToken),
                "!string.IsNullOrWhiteSpace(providerManifestToken");
            Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetEntityFrameworkVersion), "invalid entityFrameworkVersion");
            Debug.Assert(!string.IsNullOrWhiteSpace(namespaceName), "!string.IsNullOrWhiteSpace(namespaceName)");
            Debug.Assert(resolver != null, "resolver != null");

            _providerInvariantName = providerInvariantName;
            _providerManifestToken = providerManifestToken;
            _targetEntityFrameworkVersion = targetEntityFrameworkVersion;
            _namespaceName = namespaceName;
            _dependencyResolver = resolver;
            _generateForeignKeyProperties = generateForeignKeyProperties;

            var providerServices = resolver.GetService<DbProviderServices>(providerInvariantName);
            Debug.Assert(providerServices != null, "providerServices != null");

            _nameToEdmType = providerServices.GetProviderManifest(providerManifestToken)
                .GetStoreTypes()
                .ToDictionary(t => t.Name, t => t);
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Call this method from the constructor of a class derived from <see cref="DbConfiguration" /> to
        ///     add a <see cref="IDbDependencyResolver" /> instance to the Chain of Responsibility of resolvers that
        ///     are used to resolve dependencies needed by the Entity Framework.
        /// </summary>
        /// <remarks>
        ///     Resolvers are asked to resolve dependencies in reverse order from which they are added. This means
        ///     that a resolver can be added to override resolution of a dependency that would already have been
        ///     resolved in a different way.
        ///     The exceptions to this is that any dependency registered in the application's config file
        ///     will always be used in preference to using a dependency resolver added here.
        /// </remarks>
        /// <param name="resolver"> The resolver to add. </param>
        protected internal void AddDependencyResolver(IDbDependencyResolver resolver)
        {
            Check.NotNull(resolver, "resolver");

            _internalConfiguration.CheckNotLocked("AddDependencyResolver");
            _internalConfiguration.AddDependencyResolver(resolver, overrideConfigFile: false);
        }
Exemplo n.º 10
0
        public static StoreItemCollection CreateStoreItemCollection(
            string ssdl, Version targetFrameworkVersion, IDbDependencyResolver resolver, out IList <EdmSchemaError> edmErrors)
        {
            if (ssdl == null)
            {
                throw new ArgumentNullException("ssdl");
            }

            if (targetFrameworkVersion == null)
            {
                throw new ArgumentNullException("targetFrameworkVersion");
            }

            if (!EntityFrameworkVersion.IsValidVersion(targetFrameworkVersion))
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.CurrentCulture, Resources.ErrorNonValidTargetVersion, targetFrameworkVersion),
                          "targetFrameworkVersion");
            }

            using (var textReader = new StringReader(ssdl))
            {
                using (var ssdlReader = XmlReader.Create(textReader))
                {
                    return(StoreItemCollection.Create(new[] { ssdlReader }, null, resolver, out edmErrors));
                }
            }
        }
        internal static string GetProviderManifestTokenConnected(
            IDbDependencyResolver resolver, string providerInvariantName, string providerConnectionString)
        {
            DbConnection connection = null;

            try
            {
                var factory = DbProviderFactories.GetFactory(providerInvariantName);
                Debug.Assert(factory != null, "failed because DbProviderFactory is null");

                connection = factory.CreateConnection();

                Debug.Assert(connection != null, "failed because DbConnection is null");
                connection.ConnectionString = providerConnectionString;

                var providerServices = resolver.GetService <DbProviderServices>(providerInvariantName);
                Debug.Assert(providerServices != null, "failed because DbProviderServices is null");

                return(providerServices.GetProviderManifestToken(connection));
            }
            finally
            {
                VsUtils.SafeCloseDbConnection(connection, providerInvariantName, providerConnectionString);
            }
        }
Exemplo n.º 12
0
 private IList <EdmSchemaError> Init(
     IEnumerable <XmlReader> xmlReaders,
     IEnumerable <string> filePaths,
     bool throwOnError,
     IDbDependencyResolver resolver,
     out DbProviderManifest providerManifest,
     out DbProviderFactory providerFactory,
     out string providerInvariantName,
     out string providerManifestToken,
     out Memoizer <EdmFunction, EdmFunction> cachedCTypeFunction)
 {
     cachedCTypeFunction = new Memoizer <EdmFunction, EdmFunction>(new Func <EdmFunction, EdmFunction>(StoreItemCollection.ConvertFunctionSignatureToCType), (IEqualityComparer <EdmFunction>)null);
     StoreItemCollection.Loader loader = new StoreItemCollection.Loader(xmlReaders, filePaths, throwOnError, resolver);
     providerFactory       = loader.ProviderFactory;
     providerManifest      = loader.ProviderManifest;
     providerManifestToken = loader.ProviderManifestToken;
     providerInvariantName = loader.ProviderInvariantName;
     if (!loader.HasNonWarningErrors)
     {
         this.LoadProviderManifest(loader.ProviderManifest);
         List <EdmSchemaError> edmSchemaErrorList = EdmItemCollection.LoadItems(this._providerManifest, loader.Schemas, (ItemCollection)this);
         foreach (EdmSchemaError edmSchemaError in edmSchemaErrorList)
         {
             loader.Errors.Add(edmSchemaError);
         }
         if (throwOnError && edmSchemaErrorList.Count != 0)
         {
             loader.ThrowOnNonWarningErrors();
         }
     }
     return(loader.Errors);
 }
Exemplo n.º 13
0
        /// <summary>
        ///     Call this method to add a <see cref="IDbDependencyResolver" /> instance to the Chain of Responsibility
        ///     of resolvers that are used to resolve dependencies needed by the Entity Framework. Unlike the AddDependencyResolver
        ///     method, this method puts the resolver at the bottom of the Chain of Responsibility such that it will only
        ///     be used to resolve a dependency that could not be resolved by any of the other resolvers.
        /// </summary>
        /// <param name="resolver"> The resolver to add. </param>
        protected internal void AddSecondaryResolver(IDbDependencyResolver resolver)
        {
            Check.NotNull(resolver, "resolver");

            _internalConfiguration.CheckNotLocked("AddSecondaryResolver");
            _internalConfiguration.AddSecondaryResolver(resolver);
        }
Exemplo n.º 14
0
        private static bool IsCompositeResolver(IDbDependencyResolver resolver)
        {
            var type = resolver.GetType();

            return(type.IsGenericType &&
                   type.GetGenericTypeDefinition().FullName == @"System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2");
        }
        /// <summary>
        /// Call this method to add a <see cref="IDbDependencyResolver" /> instance to the Chain of Responsibility
        /// of resolvers that are used to resolve dependencies needed by the Entity Framework. Unlike the AddDependencyResolver
        /// method, this method puts the resolver at the bottom of the Chain of Responsibility such that it will only
        /// be used to resolve a dependency that could not be resolved by any of the other resolvers.
        /// </summary>
        /// <param name="resolver"> The resolver to add. </param>
        public void AddDefaultResolver(IDbDependencyResolver resolver)
        {
            Check.NotNull(resolver, "resolver");

            _internalConfiguration.CheckNotLocked("AddDefaultResolver");
            _internalConfiguration.AddDefaultResolver(resolver);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Calls <see cref="IDbDependencyResolver.GetServices" /> passing the given type argument and using
        /// null for the name argument.
        /// </summary>
        /// <param name="resolver"> The resolver to use. </param>
        /// <param name="type"> The contract type to resolve. </param>
        /// <returns> All resolved dependencies, or an <see cref="IEnumerable{Object}"/> if no services are resolved.</returns>
        public static IEnumerable <object> GetServices(this IDbDependencyResolver resolver, Type type)
        {
            Check.NotNull(resolver, "resolver");
            Check.NotNull(type, "type");

            return(resolver.GetServices(type, null));
        }
Exemplo n.º 17
0
        public DatabaseCreator(IDbDependencyResolver resolver, MigrationsChecker migrationsChecker = null)
        {
            DebugCheck.NotNull(resolver);

            _resolver          = resolver;
            _migrationsChecker = migrationsChecker ?? new MigrationsChecker();
        }
Exemplo n.º 18
0
        public virtual void AddSecondaryResolver(IDbDependencyResolver resolver)
        {
            DebugCheck.NotNull(resolver);

            // Secondary resolvers only kick in if nothing else before the root resolves the dependency.
            _rootResolver.AddSecondaryResolver(resolver);
        }
Exemplo n.º 19
0
 internal SchemaElement(
     SchemaElement parentElement,
     string name,
     IDbDependencyResolver resolver = null)
     : this(parentElement, resolver)
 {
     this._name = name;
 }
 internal static EntityCommandDefinition CreateCommandDefinition(
     DbProviderFactory storeProviderFactory,
     DbCommandTree commandTree,
     DbInterceptionContext interceptionContext,
     IDbDependencyResolver resolver = null)
 {
     return(new EntityCommandDefinition(storeProviderFactory, commandTree, interceptionContext, resolver, (BridgeDataReaderFactory)null, (ColumnMapFactory)null));
 }
Exemplo n.º 21
0
        internal static EntityCommandDefinition CreateCommandDefinition(
            DbProviderFactory storeProviderFactory, DbCommandTree commandTree, IDbDependencyResolver resolver = null)
        {
            DebugCheck.NotNull(storeProviderFactory);
            DebugCheck.NotNull(commandTree);

            return(new EntityCommandDefinition(storeProviderFactory, commandTree, resolver));
        }
        public WrappingDependencyResolver(IDbDependencyResolver snapshot, Func <TService, object, TService> serviceWrapper)
        {
            DebugCheck.NotNull(snapshot);
            DebugCheck.NotNull(serviceWrapper);

            _snapshot       = snapshot;
            _serviceWrapper = serviceWrapper;
        }
Exemplo n.º 23
0
        public virtual void AddDependencyResolver(IDbDependencyResolver resolver)
        {
            DebugCheck.NotNull(resolver);
            Debug.Assert(!_isLocked);

            // New resolvers always run after the config resolvers so that config always wins over code
            _resolvers.Second.Add(resolver);
        }
Exemplo n.º 24
0
        // Internal for testing
        internal ColumnDiscoverer(CodeHelper code, IDbDependencyResolver dependencyResolver)
        {
            Debug.Assert(code != null, "code is null.");
            Debug.Assert(dependencyResolver != null, "dependencyResolver is null.");

            _code = code;
            _dependencyResolver = dependencyResolver;
        }
Exemplo n.º 25
0
        private static IEnumerable <IDbDependencyResolver> ExplodeResolverChain(
            IDbDependencyResolver resolverChain)
        {
            var type      = resolverChain.GetType();
            var resolvers = (IEnumerable <IDbDependencyResolver>)type.GetProperty(@"Resolvers").GetValue(resolverChain, null);

            return(resolvers.SelectMany(GetInternalResolvers));
        }
Exemplo n.º 26
0
 /// <summary>
 /// Calls <see cref="M:System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver.GetServices(System.Type,System.Object)" /> passing the given type argument and using
 /// null for the name argument.
 /// </summary>
 /// <param name="resolver"> The resolver to use. </param>
 /// <param name="type"> The contract type to resolve. </param>
 /// <returns> All resolved dependencies, or an <see cref="T:System.Collections.Generic.IEnumerable`1" /> if no services are resolved.</returns>
 public static IEnumerable <object> GetServices(
     this IDbDependencyResolver resolver,
     Type type)
 {
     Check.NotNull <IDbDependencyResolver>(resolver, nameof(resolver));
     Check.NotNull <Type>(type, nameof(type));
     return(resolver.GetServices(type, (object)null));
 }
Exemplo n.º 27
0
        // <summary>
        // This is a helper method that can be used in an <see cref="IDbDependencyResolver.GetServices"/> implementation
        // such that an empty list is returned if the <see cref="IDbDependencyResolver.GetService"/> returns null
        // and a list of one element is returned if GetService returns one element.
        // </summary>
        // <param name="resolver">The resolver.</param>
        // <param name="type"> The contract type to resolve. </param>
        // <param name="key"> The key of the dependency to resolve. </param>
        // <returns>A list of either zero or one elements.</returns>
        internal static IEnumerable <object> GetServiceAsServices(this IDbDependencyResolver resolver, Type type, object key)
        {
            DebugCheck.NotNull(resolver);

            var service = resolver.GetService(type, key);

            return(service == null?Enumerable.Empty <object>() : new[] { service });
        }
Exemplo n.º 28
0
        // Internal for testing
        internal ColumnDiscoverer(CodeHelper code, IDbDependencyResolver dependencyResolver)
        {
            Debug.Assert(code != null, "code is null.");
            Debug.Assert(dependencyResolver != null, "dependencyResolver is null.");

            _code = code;
            _dependencyResolver = dependencyResolver;
        }
        internal static EntityCommandDefinition CreateCommandDefinition(
            DbProviderFactory storeProviderFactory, DbCommandTree commandTree, IDbDependencyResolver resolver = null)
        {
            DebugCheck.NotNull(storeProviderFactory);
            DebugCheck.NotNull(commandTree);

            return new EntityCommandDefinition(storeProviderFactory, commandTree, resolver);
        }
Exemplo n.º 30
0
 public GlimpseDbDependencyResolver(DbConfiguration originalDbConfiguration)
 {
     // Get the original resolver
     var internalConfigProp = originalDbConfiguration.GetType().GetProperty("InternalConfiguration", BindingFlags.Instance | BindingFlags.NonPublic);
     var internalConfig = internalConfigProp.GetValue(originalDbConfiguration, null);
     var rootResolverProp = internalConfig.GetType().GetProperty("RootResolver", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     rootResolver = (IDbDependencyResolver)rootResolverProp.GetValue(internalConfig, null);
 }
Exemplo n.º 31
0
 /// <summary>
 /// Constructs the EntityCommand object with the given eSQL statement and the connection object to use
 /// </summary>
 /// <param name="statement"> The eSQL command text to execute </param>
 /// <param name="connection"> The connection object </param>
 /// <param name="resolver"> Resolver used to resolve DbProviderServices </param>
 public EntityCommand(
     string statement,
     EntityConnection connection,
     IDbDependencyResolver resolver)
     : this(statement, connection)
 {
     this._dependencyResolver = resolver;
 }
Exemplo n.º 32
0
 private StoreItemCollection(
     IEnumerable <XmlReader> xmlReaders,
     ReadOnlyCollection <string> filePaths,
     IDbDependencyResolver resolver,
     out IList <EdmSchemaError> errors)
     : base(DataSpace.SSpace)
 {
     errors = this.Init(xmlReaders, (IEnumerable <string>)filePaths, false, resolver, out this._providerManifest, out this._providerFactory, out this._providerInvariantName, out this._providerManifestToken, out this._cachedCTypeFunction);
 }
        internal static DbSpatialServices GetSpatialServices(
            IDbDependencyResolver resolver,
            EntityConnection connection)
        {
            StoreItemCollection itemCollection = (StoreItemCollection)connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace);
            DbProviderInfo      key            = new DbProviderInfo(itemCollection.ProviderInvariantName, itemCollection.ProviderManifestToken);

            return(DbProviderServices.GetSpatialServices(resolver, key, (Func <DbProviderServices>)(() => DbProviderServices.GetProviderServices(connection.StoreConnection))));
        }
Exemplo n.º 34
0
        public GlimpseDbDependencyResolver(DbConfiguration originalDbConfiguration)
        {
            // Get the original resolver
            var internalConfigProp = originalDbConfiguration.GetType().GetProperty("InternalConfiguration", BindingFlags.Instance | BindingFlags.NonPublic);
            var internalConfig     = internalConfigProp.GetValue(originalDbConfiguration, null);
            var rootResolverProp   = internalConfig.GetType().GetProperty("RootResolver", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

            rootResolver = (IDbDependencyResolver)rootResolverProp.GetValue(internalConfig, null);
        }
Exemplo n.º 35
0
        public virtual void AddDependencyResolver(IDbDependencyResolver resolver, bool overrideConfigFile = false)
        {
            DebugCheck.NotNull(resolver);
            Debug.Assert(!_isLocked);

            // New resolvers always run after the config resolvers so that config always wins over code
            // unless the override flag is used, in which case we add the new resolver right at the top.
            (overrideConfigFile ? _resolvers.First : _resolvers.Second).Add(resolver);
        }
Exemplo n.º 36
0
        internal EdmXmlSchemaWriter(XmlWriter xmlWriter, double edmVersion, bool serializeDefaultNullability, IDbDependencyResolver resolver = null)
        {
            DebugCheck.NotNull(xmlWriter);

            _resolver = resolver ?? DbConfiguration.DependencyResolver;
            _serializeDefaultNullability = serializeDefaultNullability;
            _xmlWriter = xmlWriter;
            _version   = edmVersion;
        }
        // TODO: targetEntityFrameworkRuntimeVersion is not correct and can be based on the target .NET Fx version or the namespace of the edmx file
        internal RuntimeMetadataValidator(
            ModelManager modelManager, Version targetEntityFrameworkRuntimeVersion, IDbDependencyResolver dependencyResolver)
        {
            Debug.Assert(modelManager != null, "modelManager != null");
            Debug.Assert(targetEntityFrameworkRuntimeVersion != null, "targetEntityFrameworkRuntimeVersion != null");

            _modelManager = modelManager;
            _targetEntityFrameworkRuntimeVersion = targetEntityFrameworkRuntimeVersion;
            _dependencyResolver = dependencyResolver;
        }
        static StoreModelBuilderTests()
        {
            var mockResolver = new Mock<IDbDependencyResolver>();
            mockResolver.Setup(
                r => r.GetService(
                    It.Is<Type>(t => t == typeof(DbProviderServices)),
                    It.IsAny<string>())).Returns(SqlProviderServices.Instance);

            DependencyResolver = mockResolver.Object;
        }
Exemplo n.º 39
0
        /// <summary>
        ///     Adds a new resolver to the top of the chain.
        /// </summary>
        /// <param name="resolver">The resolver to add.</param>
        public virtual void Add(IDbDependencyResolver resolver)
        {
            Check.NotNull(resolver, "resolver");

            // The idea here is that Add and GetService must all be thread-safe, but
            // Add is only called infrequently. Therefore each time Add is called a snapshot is taken
            // of the stack that can then be enumerated without needing to make a snapshot
            // every time the enumeration is asked for, which is the normal behavior for the concurrent
            // collections.
            _resolvers.Push(resolver);
            _resolversSnapshot = _resolvers.ToArray();
        }
            public Loader(
                IEnumerable<XmlReader> xmlReaders, IEnumerable<string> sourceFilePaths, bool throwOnError, IDbDependencyResolver resolver)
            {
                _throwOnError = throwOnError;
                _resolver = resolver ==
                            null
                                ? DbConfiguration.DependencyResolver
                                : new CompositeResolver<IDbDependencyResolver, IDbDependencyResolver>(
                                      resolver, DbConfiguration.DependencyResolver);

                LoadItems(xmlReaders, sourceFilePaths);
            }
Exemplo n.º 41
0
        public EdmExtensionTests()
        {
            var providerServices =
                new LegacyDbProviderServicesWrapper(
                    ((Legacy.DbProviderServices)
                     ((IServiceProvider)Legacy.DbProviderFactories.GetFactory("System.Data.SqlClient"))
                         .GetService(typeof(Legacy.DbProviderServices))));

            var mockResolver = new Mock<IDbDependencyResolver>();
            mockResolver.Setup(
                r => r.GetService(
                    It.Is<Type>(t => t == typeof(DbProviderServices)),
                    It.IsAny<string>())).Returns(providerServices);

            resolver = mockResolver.Object;
        }
Exemplo n.º 42
0
        // <summary>
        // constructor that loads the metadata files from the specified xmlReaders, and returns the list of errors
        // encountered during load as the out parameter errors.
        // </summary>
        // <param name="xmlReaders">xmlReaders where the CDM schemas are loaded</param>
        // <param name="filePaths">the paths where the files can be found that match the xml readers collection</param>
        // <param name="errors">An out parameter to return the collection of errors encountered while loading</param>
        private StoreItemCollection(
            IEnumerable<XmlReader> xmlReaders,
            ReadOnlyCollection<string> filePaths,
            IDbDependencyResolver resolver,
            out IList<EdmSchemaError> errors)
            : base(DataSpace.SSpace)
        {
            DebugCheck.NotNull(xmlReaders);

            errors = Init(
                xmlReaders, filePaths, /* throwOnError */ false, resolver,
                out _providerManifest,
                out _providerFactory,
                out _providerInvariantName,
                out _providerManifestToken,
                out _cachedCTypeFunction);
        }
        private void CreateDatabase_uses_Migrations_when_provider_is_known(string provider, IDbDependencyResolver resolver = null)
        {
            var mockOperations = new Mock<DatabaseOperations>();
            var mockContext = CreateMockContextForMigrator(mockOperations);
            mockContext.Setup(m => m.ProviderName).Returns(provider);

            Mock<MigratorBase> mockMigrator = null;

            new DatabaseCreator(new Lazy<IDbDependencyResolver>(() => resolver ?? DbConfiguration.Instance.DependencyResolver))
                .CreateDatabase(
                    mockContext.Object,
                    (config, context) => (mockMigrator = new Mock<MigratorBase>(null)).Object,
                    null);

            mockMigrator.Verify(m => m.Update(null), Times.Once());
            mockOperations.Verify(m => m.Create(null), Times.Never());
            mockContext.Verify(m => m.SaveMetadataToDatabase(), Times.Never());
            mockContext.Verify(m => m.MarkDatabaseInitialized(), Times.Once());
        }
        /// <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);
        }
Exemplo n.º 45
0
        public static DbProviderManifest GetProviderManifest(
            this DbModel model,
            IDbDependencyResolver dependencyResolver)
        {
            Debug.Assert(model != null, "model is null.");
            Debug.Assert(dependencyResolver != null, "dependencyResolver is null.");

            if (model.ProviderManifest != null)
            {
                return model.ProviderManifest;
            }

            DbProviderManifest providerManifest;
            if (!_providerManifestCache.TryGetValue(model.ProviderInfo, out providerManifest))
            {
                providerManifest = dependencyResolver
                    .GetService<DbProviderServices>(model.ProviderInfo.ProviderInvariantName)
                    .GetProviderManifest(model.ProviderInfo.ProviderManifestToken);
                _providerManifestCache.Add(model.ProviderInfo, providerManifest);
            }

            return providerManifest;
        }
        internal static DbSpatialServices GetSpatialServices(IDbDependencyResolver resolver, EntityConnection connection)
        {
            DebugCheck.NotNull(resolver);
            DebugCheck.NotNull(connection);

            var storeItemCollection = (StoreItemCollection)connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace);
            var key = new DbProviderInfo(
                storeItemCollection.StoreProviderInvariantName, storeItemCollection.StoreProviderManifestToken);

            return GetSpatialServices(resolver, key, () => GetProviderServices(connection.StoreConnection));
        }
        public virtual void AddDefaultResolver(IDbDependencyResolver resolver)
        {
            DebugCheck.NotNull(resolver);

            _defaultResolvers.Add(resolver);
        }
Exemplo n.º 48
0
        /// <summary>
        ///     Constructs an EF provider that will use the given <see cref="IDbDependencyResolver" /> for
        ///     resolving EF dependencies such as the <see cref="DbSpatialServices" /> instance to use.
        /// </summary>
        /// <param name="resolver"> The resolver to use. </param>
        protected DbProviderServices(IDbDependencyResolver resolver)
        {
            Contract.Requires(resolver != null);

            _resolver = new Lazy<IDbDependencyResolver>(() => resolver);
        }
Exemplo n.º 49
0
        /// <summary>
        /// Factory method that creates a <see cref="StoreItemCollection" />.
        /// </summary>
        /// <param name="xmlReaders">
        /// SSDL artifacts to load. Must not be <c>null</c>.
        /// </param>
        /// <param name="filePaths">
        /// Paths to SSDL artifacts. Used in error messages. Can be <c>null</c> in which case
        /// the base Uri of the XmlReader will be used as a path.
        /// </param>
        /// <param name="resolver">
        /// Custom resolver. Currently used to resolve DbProviderServices implementation. If <c>null</c>
        /// the default resolver will be used.
        /// </param>
        /// <param name="errors">
        /// The collection of errors encountered while loading.
        /// </param>
        /// <returns>
        /// <see cref="StoreItemCollection" /> instance if no errors encountered. Otherwise <c>null</c>.
        /// </returns>
        public static StoreItemCollection Create(
            IEnumerable<XmlReader> xmlReaders,
            ReadOnlyCollection<string> filePaths,
            IDbDependencyResolver resolver,
            out IList<EdmSchemaError> errors)
        {
            Check.NotNull(xmlReaders, "xmlReaders");
            EntityUtil.CheckArgumentContainsNull(ref xmlReaders, "xmlReaders");
            EntityUtil.CheckArgumentEmpty(ref xmlReaders, Strings.StoreItemCollectionMustHaveOneArtifact, "xmlReaders");

            var storeItemCollection = new StoreItemCollection(xmlReaders, filePaths, resolver, out errors);

            return errors != null && errors.Count > 0 ? null : storeItemCollection;
        }
        /// <summary>
        ///     Adds an <see cref="IDbDependencyResolver" /> that will be used to resolve secondary provider
        ///     services when a derived type is registered as an EF provider either using an entry in the application's
        ///     config file or through code-based registeration in <see cref="DbConfiguration" />.
        /// </summary>
        /// <param name="resolver">The resolver to add.</param>
        protected void AddDependencyResolver(IDbDependencyResolver resolver)
        {
            Check.NotNull(resolver, "resolver");

            _resolvers.Add(resolver);
        }
        private static DbSpatialServices GetSpatialServices(
            IDbDependencyResolver resolver,
            DbProviderInfo key,
            Func<DbProviderServices> providerServices) // Delegate use to avoid lookup when not needed
        {
            DebugCheck.NotNull(resolver);
            DebugCheck.NotNull(key);
            DebugCheck.NotNull(providerServices);

            var services = _spatialServices.GetOrAdd(
                key,
                k =>
                resolver.GetService<DbSpatialServices>(k)
                ?? providerServices().GetSpatialServicesInternal(k.ProviderManifestToken, throwIfNotImplemented: false)
                ?? resolver.GetService<DbSpatialServices>());

            if (services == null)
            {
                throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices);
            }
            return services;
        }
        internal EntityCommandDefinition(
            DbProviderFactory storeProviderFactory,
            DbCommandTree commandTree, 
            DbInterceptionContext interceptionContext,
            IDbDependencyResolver resolver = null,
            BridgeDataReaderFactory bridgeDataReaderFactory = null,
            ColumnMapFactory columnMapFactory = null)
        {
            DebugCheck.NotNull(storeProviderFactory);
            DebugCheck.NotNull(commandTree);
            DebugCheck.NotNull(interceptionContext);

            _bridgeDataReaderFactory = bridgeDataReaderFactory ?? new BridgeDataReaderFactory();
            _columnMapFactory = columnMapFactory ?? new ColumnMapFactory();

            _storeProviderServices =
                (resolver != null
                     ? resolver.GetService<DbProviderServices>(storeProviderFactory.GetProviderInvariantName())
                     : null) ??
                storeProviderFactory.GetProviderServices();

            try
            {
                if (DbCommandTreeKind.Query
                    == commandTree.CommandTreeKind)
                {
                    // Next compile the plan for the command tree
                    var mappedCommandList = new List<ProviderCommandInfo>();
                    ColumnMap columnMap;
                    int columnCount;
                    PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets);
                    _columnMapGenerators = new IColumnMapGenerator[] { new ConstantColumnMapGenerator(columnMap, columnCount) };
                    // Note: we presume that the first item in the ProviderCommandInfo is the root node;
                    Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?");
                    // this shouldn't ever happen.

                    // Then, generate the store commands from the resulting command tree(s)
                    _mappedCommandDefinitions = new List<DbCommandDefinition>(mappedCommandList.Count);

                    foreach (var providerCommandInfo in mappedCommandList)
                    {
                        var providerCommandDefinition = _storeProviderServices.CreateCommandDefinition(
                            providerCommandInfo.CommandTree, interceptionContext);

                        if (null == providerCommandDefinition)
                        {
                            throw new ProviderIncompatibleException(Strings.ProviderReturnedNullForCreateCommandDefinition);
                        }

                        _mappedCommandDefinitions.Add(providerCommandDefinition);
                    }
                }
                else
                {
                    Debug.Assert(
                        DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported");
                    var entityCommandTree = (DbFunctionCommandTree)commandTree;

                    // Retrieve mapping and metadata information for the function import.
                    var mapping = GetTargetFunctionMapping(entityCommandTree);
                    IList<FunctionParameter> returnParameters = entityCommandTree.EdmFunction.ReturnParameters;
                    var resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1;
                    _columnMapGenerators = new IColumnMapGenerator[resultSetCount];
                    var storeResultType = DetermineStoreResultType(mapping, 0, out _columnMapGenerators[0]);
                    for (var i = 1; i < resultSetCount; i++)
                    {
                        DetermineStoreResultType(mapping, i, out _columnMapGenerators[i]);
                    }

                    // Copy over parameters (this happens through a more indirect route in the plan compiler, but
                    // it happens nonetheless)
                    var providerParameters = new List<KeyValuePair<string, TypeUsage>>();
                    foreach (var parameter in entityCommandTree.Parameters)
                    {
                        providerParameters.Add(parameter);
                    }

                    // Construct store command tree usage.
                    var providerCommandTree = new DbFunctionCommandTree(
                        entityCommandTree.MetadataWorkspace, DataSpace.SSpace,
                        mapping.TargetFunction, storeResultType, providerParameters);

                    var storeCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandTree);
                    _mappedCommandDefinitions = new List<DbCommandDefinition>(1)
                        {
                            storeCommandDefinition
                        };

                    var firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault();
                    if (firstResultEntitySet != null)
                    {
                        _entitySets = new Set<EntitySet>();
                        _entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault());
                        _entitySets.MakeReadOnly();
                    }
                }

                // Finally, build a list of the parameters that the resulting command should have;
                var parameterList = new List<EntityParameter>();

                foreach (var queryParameter in commandTree.Parameters)
                {
                    var parameter = CreateEntityParameterFromQueryParameter(queryParameter);
                    parameterList.Add(parameter);
                }

                _parameters = new ReadOnlyCollection<EntityParameter>(parameterList);
            }
            catch (EntityCommandCompilationException)
            {
                // No need to re-wrap EntityCommandCompilationException
                throw;
            }
            catch (Exception e)
            {
                // we should not be wrapping all exceptions
                if (e.IsCatchableExceptionType())
                {
                    // we don't wan't folks to have to know all the various types of exceptions that can 
                    // occur, so we just rethrow a CommandDefinitionException and make whatever we caught  
                    // the inner exception of it.
                    throw new EntityCommandCompilationException(Strings.EntityClient_CommandDefinitionPreparationFailed, e);
                }

                throw;
            }
        }
Exemplo n.º 53
0
        public DatabaseCreator(IDbDependencyResolver resolver)
        {
            DebugCheck.NotNull(resolver);

            _resolver = resolver;
        }
        public CachingDependencyResolver(IDbDependencyResolver underlyingResolver)
        {
            //Contract.Requires(underlyingResolver != null);

            _underlyingResolver = underlyingResolver;
        }
 public SpatialServicesLoader(IDbDependencyResolver resolver)
 {
     _resolver = resolver;
 }
        public virtual void AddSecondaryResolver(IDbDependencyResolver resolver)
        {
            DebugCheck.NotNull(resolver);

            _secondaryResolvers.Add(resolver);
        }
Exemplo n.º 57
0
        private IList<EdmSchemaError> Init(
            IEnumerable<XmlReader> xmlReaders,
            IEnumerable<string> filePaths,
            bool throwOnError,
            IDbDependencyResolver resolver,
            out DbProviderManifest providerManifest,
            out DbProviderFactory providerFactory,
            out string providerInvariantName,
            out string providerManifestToken,
            out Memoizer<EdmFunction, EdmFunction> cachedCTypeFunction)
        {
            DebugCheck.NotNull(xmlReaders);
            // 'filePaths' can be null

            cachedCTypeFunction = new Memoizer<EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);

            var loader = new Loader(xmlReaders, filePaths, throwOnError, resolver);
            providerFactory = loader.ProviderFactory;
            providerManifest = loader.ProviderManifest;
            providerManifestToken = loader.ProviderManifestToken;
            providerInvariantName = loader.ProviderInvariantName;

            // load the items into the colleciton
            if (!loader.HasNonWarningErrors)
            {
                LoadProviderManifest(loader.ProviderManifest /* check for system namespace */);
                var errorList = EdmItemCollection.LoadItems(_providerManifest, loader.Schemas, this);
                foreach (var error in errorList)
                {
                    loader.Errors.Add(error);
                }

                if (throwOnError && errorList.Count != 0)
                {
                    loader.ThrowOnNonWarningErrors();
                }
            }

            return loader.Errors;
        }
Exemplo n.º 58
0
        private static Mock<InternalConfiguration> CreateMockInternalConfiguration(
            DbConfiguration dbConfiguration = null, IDbDependencyResolver snapshot = null)
        {
            var mockInternalConfiguration = new Mock<InternalConfiguration>(null, null, null, null);

            if (dbConfiguration == null)
            {
                var mockDbConfiguration = new Mock<DbConfiguration>();
                mockDbConfiguration.Setup(m => m.InternalConfiguration).Returns(mockInternalConfiguration.Object);
                dbConfiguration = mockDbConfiguration.Object;
            }

            mockInternalConfiguration.Setup(m => m.Owner).Returns(dbConfiguration);
            mockInternalConfiguration.Setup(m => m.ResolverSnapshot).Returns(snapshot);

            return mockInternalConfiguration;
        }
 public new void AddDependencyResolver(IDbDependencyResolver resolver)
 {
     base.AddDependencyResolver(resolver);
 }
Exemplo n.º 60
0
        private static DbSpatialServices GetSpatialServices(
            IDbDependencyResolver resolver,
            DbProviderInfo key,
            Func<DbProviderServices> providerServices) // Delegate use to avoid lookup when not needed
        {
            DebugCheck.NotNull(resolver);
            DebugCheck.NotNull(key);
            DebugCheck.NotNull(providerServices);

#pragma warning disable 612, 618
            var services = _spatialServices.GetOrAdd(
                key,
                k => resolver.GetService<DbSpatialServices>(k)
                     ?? providerServices().GetSpatialServices(k.ProviderManifestToken)
                     ?? resolver.GetService<DbSpatialServices>());
#pragma warning restore 612, 618

            if (services == null)
            {
                throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices);
            }
            return services;
        }