public override void CollectFilePermissionPaths(List <string> paths, DataSpace spaceToGet)
 {
     if (!_alreadyLoaded && MetadataArtifactLoader.IsArtifactOfDataSpace(_path, spaceToGet))
     {
         paths.Add(_path);
     }
 }
        internal static MetadataArtifactLoader CreateResourceLoader(string path, ExtensionCheck extensionCheck, string validExtension, ICollection <string> uriRegistry, MetadataArtifactAssemblyResolver resolver)
        {
            Debug.Assert(path != null);
            Debug.Assert(MetadataArtifactLoader.PathStartsWithResPrefix(path));

            // if the supplied path ends with a separator, or contains only one
            // segment (i.e., the name of an assembly, or the wildcard character),
            // create a composite loader that can extract resources from one or
            // more assemblies
            //
            bool   createCompositeResLoader = false;
            string assemblyName             = null;
            string resourceName             = null;

            ParseResourcePath(path, out assemblyName, out resourceName);
            createCompositeResLoader = (assemblyName != null) && (resourceName == null || assemblyName.Trim() == wildcard);

            ValidateExtension(extensionCheck, validExtension, resourceName);

            if (createCompositeResLoader)
            {
                return(new MetadataArtifactLoaderCompositeResource(path, assemblyName, resourceName, uriRegistry, resolver));
            }

            Debug.Assert(!string.IsNullOrEmpty(resourceName), "we should not get here is the resourceName is null");
            Assembly assembly = ResolveAssemblyName(assemblyName, resolver);

            return(new MetadataArtifactLoaderResource(assembly, resourceName, uriRegistry));
        }
Esempio n. 3
0
            internal void LoadEdmItemCollection(MetadataArtifactLoader loader)
            {
                Debug.Assert(loader != null, "loader is null");

                List <XmlReader> readers = loader.CreateReaders(DataSpace.CSpace);

                try
                {
                    EdmItemCollection itemCollection = new EdmItemCollection(
                        readers,
                        loader.GetPaths(DataSpace.CSpace)
                        );

                    List <string> permissionPaths = new List <string>();
                    loader.CollectFilePermissionPaths(permissionPaths, DataSpace.CSpace);
                    FileIOPermission filePermissions = null;
                    if (permissionPaths.Count > 0)
                    {
                        filePermissions = new FileIOPermission(FileIOPermissionAccess.Read, permissionPaths.ToArray());
                    }

                    UpdateMetadataEntry(itemCollection, filePermissions);
                }
                finally
                {
                    Helper.DisposeXmlReaders(readers);
                }
            }
Esempio n. 4
0
        [ResourceConsumption(ResourceScope.Machine)] //For MetadataArtifactLoader.CreateCompositeFromFilePaths method call but we do not create the file paths in this method
        public EdmItemCollection(params string[] filePaths)
            : base(DataSpace.CSpace)
        {
            EntityUtil.CheckArgumentNull(filePaths, "filePaths");

            // Wrap the file paths in instances of the MetadataArtifactLoader class, which provides
            // an abstraction and a uniform interface over a diverse set of metadata artifacts.
            //
            MetadataArtifactLoader composite = null;
            List <XmlReader>       readers   = null;

            try
            {
                composite = MetadataArtifactLoader.CreateCompositeFromFilePaths(filePaths, XmlConstants.CSpaceSchemaExtension);
                readers   = composite.CreateReaders(DataSpace.CSpace);
                this.Init(readers,
                          composite.GetPaths(DataSpace.CSpace),
                          true /*throwOnError*/);
            }
            finally
            {
                if (readers != null)
                {
                    Helper.DisposeXmlReaders(readers);
                }
            }
        }
Esempio n. 5
0
            internal void LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
            {
                StoreItemCollection     storeItemCollection = null;
                IEnumerable <XmlReader> sSpaceXmlReaders    = loader.CreateReaders(DataSpace.SSpace);

                try
                {
                    // Load the store side, however, only do so if we don't already have one
                    storeItemCollection = new StoreItemCollection(
                        sSpaceXmlReaders,
                        loader.GetPaths(DataSpace.SSpace));
                }
                finally
                {
                    Helper.DisposeXmlReaders(sSpaceXmlReaders);
                }

                // If this entry is getting re-used, make sure that the previous query cache manager gets
                // cleared up
                if (_queryCacheManager != null)
                {
                    _queryCacheManager.Clear();
                }

                // Update the query cache manager reference
                _queryCacheManager = storeItemCollection.QueryCacheManager;

                // With the store metadata in place, we can then load the mappings, however, only use it
                // if we don't already have one
                //
                StorageMappingItemCollection storageMappingItemCollection = null;
                IEnumerable <XmlReader>      csSpaceXmlReaders            = loader.CreateReaders(DataSpace.CSSpace);

                try
                {
                    storageMappingItemCollection = new StorageMappingItemCollection(
                        edmItemCollection,
                        storeItemCollection,
                        csSpaceXmlReaders,
                        loader.GetPaths(DataSpace.CSSpace));
                }
                finally
                {
                    Helper.DisposeXmlReaders(csSpaceXmlReaders);
                }

                List <string> permissionPaths = new List <string>();

                loader.CollectFilePermissionPaths(permissionPaths, DataSpace.SSpace);
                loader.CollectFilePermissionPaths(permissionPaths, DataSpace.CSSpace);
                FileIOPermission filePermissions = null;

                if (permissionPaths.Count > 0)
                {
                    filePermissions = new FileIOPermission(FileIOPermissionAccess.Read, permissionPaths.ToArray());
                }
                this.UpdateMetadataEntry(storageMappingItemCollection, filePermissions);
            }
        /// <summary>
        /// Get paths to artifacts for a specific DataSpace, in the original, unexpanded
        /// form
        /// </summary>
        /// <param name="spaceToGet">The DataSpace for the artifacts of interest</param>
        /// <returns>A List of strings identifying paths to all artifacts for a specific DataSpace</returns>
        public virtual List <string> GetOriginalPaths(DataSpace spaceToGet)
        {
            List <string> list = new List <string>();

            if (MetadataArtifactLoader.IsArtifactOfDataSpace(Path, spaceToGet))
            {
                list.Add(Path);
            }
            return(list);
        }
        /// <summary>
        /// Get paths to artifacts for a specific DataSpace.
        /// </summary>
        /// <param name="spaceToGet">The DataSpace for the artifacts of interest</param>
        /// <returns>A List of strings identifying paths to all artifacts for a specific DataSpace</returns>
        public override List <string> GetPaths(DataSpace spaceToGet)
        {
            List <string> list = new List <string>();

            if (MetadataArtifactLoader.IsArtifactOfDataSpace(Path, spaceToGet))
            {
                list.Add(Path);
            }
            return(list);
        }
        /// <summary>
        /// Create and return an XmlReader around the resource represented by this instance
        /// if it is of the requested DataSpace type.
        /// </summary>
        /// <param name="spaceToGet">The DataSpace corresponding to the requested artifacts</param>
        /// <returns>A List of XmlReader objects</returns>
        public override List <XmlReader> CreateReaders(DataSpace spaceToGet)
        {
            List <XmlReader> list = new List <XmlReader>();

            if (MetadataArtifactLoader.IsArtifactOfDataSpace(Path, spaceToGet))
            {
                list.Add(_reader);
            }

            return(list);
        }
        /// <summary>
        /// Create and return an XmlReader around the file represented by this instance
        /// if it is of the requested DataSpace type.
        /// </summary>
        /// <param name="spaceToGet">The DataSpace corresponding to the requested artifacts</param>
        /// <returns>A List of XmlReader objects</returns>
        public override List <XmlReader> CreateReaders(DataSpace spaceToGet)
        {
            List <XmlReader> list = new List <XmlReader>();

            if (!_alreadyLoaded && MetadataArtifactLoader.IsArtifactOfDataSpace(_path, spaceToGet))
            {
                XmlReader reader = CreateXmlReader();
                list.Add(reader);
            }
            return(list);
        }
Esempio n. 10
0
        /// <summary>
        /// Retrieves an cache entry holding to edm metadata for a given cache key
        /// </summary>
        /// <param name="cacheKey">string containing all the files from which edm metadata is to be retrieved</param>
        /// <param name="composite">An instance of the composite MetadataArtifactLoader</param>
        /// <param name="entryToken">The metadata entry token for the returned entry</param>
        /// <returns>Returns the entry containing the edm metadata</returns>
        internal static EdmItemCollection GetOrCreateEdmItemCollection(string cacheKey,
                                                                       MetadataArtifactLoader loader,
                                                                       out object entryToken)
        {
            EdmMetadataEntry entry = GetCacheEntry <EdmMetadataEntry>(_edmLevelCache, cacheKey, _edmLevelLock,
                                                                      new EdmMetadataEntryConstructor(), out entryToken);

            // Load the edm item collection or if the collection is already loaded, check for security permission
            LoadItemCollection(new EdmItemCollectionLoader(loader), entry);

            return(entry.EdmItemCollection);
        }
Esempio n. 11
0
        /// <summary>
        /// Public constructor that loads the metadata files from the specified XmlReaders
        /// </summary>
        /// <param name="xmlReaders">XmlReader objects where the EDM schemas are loaded</param>
        public EdmItemCollection(IEnumerable <XmlReader> xmlReaders)
            : base(DataSpace.CSpace)
        {
            EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders");
            EntityUtil.CheckArgumentContainsNull(ref xmlReaders, "xmlReaders");

            MetadataArtifactLoader composite = MetadataArtifactLoader.CreateCompositeFromXmlReaders(xmlReaders);

            this.Init(composite.GetReaders(),
                      composite.GetPaths(),
                      true /*throwOnError*/);
        }
Esempio n. 12
0
            /// <summary>
            /// Constructs a struct from which you can load edm item collection
            /// </summary>
            /// <param name="factory"></param>
            /// <param name="edmItemCollection"></param>
            internal StoreItemCollectionLoader(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
            {
                Debug.Assert(edmItemCollection != null, "EdmItemCollection must never be null");
                Debug.Assert(loader != null, "loader must never be null");
                //StoreItemCollection requires atleast one SSDL path.
                if ((loader.GetPaths(DataSpace.SSpace) == null) || (loader.GetPaths(DataSpace.SSpace).Count == 0))
                {
                    throw EntityUtil.Metadata(Strings.AtleastOneSSDLNeeded);
                }

                _edmItemCollection = edmItemCollection;
                _loader            = loader;
            }
Esempio n. 13
0
        /// <summary>
        /// Retrieves an entry holding store metadata for a given cache key
        /// </summary>
        /// <param name="cacheKey">The connection string whose store metadata is to be retrieved</param>
        /// <param name="composite">An instance of the composite MetadataArtifactLoader</param>
        /// <param name="entryToken">The metadata entry token for the returned entry</param>
        /// <returns>the entry containing the information on how to load store metadata</returns>
        internal static StorageMappingItemCollection GetOrCreateStoreAndMappingItemCollections(
            string cacheKey,
            MetadataArtifactLoader loader,
            EdmItemCollection edmItemCollection,
            out object entryToken)
        {
            StoreMetadataEntry entry = GetCacheEntry <StoreMetadataEntry>(_storeLevelCache, cacheKey, _storeLevelLock,
                                                                          new StoreMetadataEntryConstructor(), out entryToken);

            // Load the store item collection or if the collection is already loaded, check for security permission
            LoadItemCollection(new StoreItemCollectionLoader(edmItemCollection, loader), entry);

            return(entry.StorageMappingItemCollection);
        }
Esempio n. 14
0
        /// <summary>
        /// Public constructor that loads the metadata files from the specified xmlReaders.
        /// Throws when encounter errors.
        /// </summary>
        /// <param name="xmlReaders">xmlReaders where the CDM schemas are loaded</param>
        public StoreItemCollection(IEnumerable <XmlReader> xmlReaders)
            : base(DataSpace.SSpace)
        {
            EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders");
            EntityUtil.CheckArgumentEmpty(ref xmlReaders, Strings.StoreItemCollectionMustHaveOneArtifact, "xmlReader");

            MetadataArtifactLoader composite = MetadataArtifactLoader.CreateCompositeFromXmlReaders(xmlReaders);

            this.Init(composite.GetReaders(),
                      composite.GetPaths(), true,
                      out _providerManifest,
                      out _providerFactory,
                      out _providerManifestToken,
                      out _cachedCTypeFunction);
        }
        /// <summary>
        /// Helper method that wraps a collection of XmlReader objects in MetadataArtifactLoader
        /// instances.
        /// </summary>
        /// <param name="filePaths">The collection of XmlReader objects to wrap</param>
        /// <returns>An instance of MetadataArtifactLoader</returns>
        public static MetadataArtifactLoader CreateCompositeFromXmlReaders(IEnumerable <XmlReader> xmlReaders)
        {
            List <MetadataArtifactLoader> loaders = new List <MetadataArtifactLoader>();

            foreach (XmlReader reader in xmlReaders)
            {
                if (reader == null)
                {
                    throw EntityUtil.CollectionParameterElementIsNull("xmlReaders");
                }

                loaders.Add(new MetadataArtifactLoaderXmlReaderWrapper(reader));
            }

            return(MetadataArtifactLoader.Create(loaders));
        }
        [ResourceConsumption(ResourceScope.Machine)] //For CheckArtifactExtension method call. But the path is not created in this method.
        internal static MetadataArtifactLoader Create(string path,
                                                      ExtensionCheck extensionCheck,
                                                      string validExtension,
                                                      ICollection <string> uriRegistry,
                                                      MetadataArtifactAssemblyResolver resolver)
        {
            Debug.Assert(path != null);
            Debug.Assert(resolver != null);

            // res:// -based artifacts
            //
            if (MetadataArtifactLoader.PathStartsWithResPrefix(path))
            {
                return(MetadataArtifactLoaderCompositeResource.CreateResourceLoader(path, extensionCheck, validExtension, uriRegistry, resolver));
            }

            // Files and Folders
            //
            string normalizedPath = MetadataArtifactLoader.NormalizeFilePaths(path);

            if (Directory.Exists(normalizedPath))
            {
                return(new MetadataArtifactLoaderCompositeFile(normalizedPath, uriRegistry));
            }
            else if (File.Exists(normalizedPath))
            {
                switch (extensionCheck)
                {
                case ExtensionCheck.Specific:
                    CheckArtifactExtension(normalizedPath, validExtension);
                    break;

                case ExtensionCheck.All:
                    if (!MetadataArtifactLoader.IsValidArtifact(normalizedPath))
                    {
                        throw EntityUtil.Metadata(Strings.InvalidMetadataPath);
                    }
                    break;
                }

                return(new MetadataArtifactLoaderFile(normalizedPath, uriRegistry));
            }

            throw EntityUtil.Metadata(Strings.InvalidMetadataPath);
        }
        /// <summary>
        /// This helper method accepts a resource URI and a value from the DataSpace enum
        /// and determines whether the resource identifies an artifact of that DataSpace.
        /// </summary>
        /// <param name="resource">A URI to an artifact resource</param>
        /// <param name="dataSpace">A DataSpace enum value</param>
        /// <returns>true if the resource identifies an artifact of the specified DataSpace</returns>
        protected static bool IsArtifactOfDataSpace(string resource, DataSpace dataSpace)
        {
            if (dataSpace == DataSpace.CSpace)
            {
                return(MetadataArtifactLoader.IsCSpaceArtifact(resource));
            }

            if (dataSpace == DataSpace.SSpace)
            {
                return(MetadataArtifactLoader.IsSSpaceArtifact(resource));
            }

            if (dataSpace == DataSpace.CSSpace)
            {
                return(MetadataArtifactLoader.IsCSSpaceArtifact(resource));
            }

            Debug.Assert(false, "Invalid DataSpace specified.");
            return(false);
        }
        [ResourceConsumption(ResourceScope.Machine)] //For Create method call. But the paths are not created in this method.
        internal static MetadataArtifactLoader CreateCompositeFromFilePaths(IEnumerable <string> filePaths, string validExtension, MetadataArtifactAssemblyResolver resolver)
        {
            ExtensionCheck extensionCheck;

            if (string.IsNullOrEmpty(validExtension))
            {
                extensionCheck = ExtensionCheck.All;
            }
            else
            {
                extensionCheck = ExtensionCheck.Specific;
            }

            List <MetadataArtifactLoader> loaders = new List <MetadataArtifactLoader>();

            // The following set is used to remove duplicate paths from the incoming array
            HashSet <string> uriRegistry = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (string path in filePaths)
            {
                if (string.IsNullOrEmpty(path))
                {
                    throw EntityUtil.Metadata(System.Data.Entity.Strings.NotValidInputPath,
                                              EntityUtil.CollectionParameterElementIsNullOrEmpty("filePaths"));
                }

                string trimedPath = path.Trim();
                if (trimedPath.Length > 0)
                {
                    loaders.Add(MetadataArtifactLoader.Create(
                                    trimedPath,
                                    extensionCheck,
                                    validExtension,
                                    uriRegistry,
                                    resolver)
                                );
                }
            }

            return(MetadataArtifactLoader.Create(loaders));
        }
        private static void ValidateExtension(ExtensionCheck extensionCheck, string validExtension, string resourceName)
        {
            if (resourceName == null)
            {
                return;
            }

            // the supplied path represents a single resource
            //
            switch (extensionCheck)
            {
            case ExtensionCheck.Specific:
                MetadataArtifactLoader.CheckArtifactExtension(resourceName, validExtension);
                break;

            case ExtensionCheck.All:
                if (!MetadataArtifactLoader.IsValidArtifact(resourceName))
                {
                    throw EntityUtil.Metadata(Strings.InvalidMetadataPath);
                }
                break;
            }
        }
Esempio n. 20
0
        [ResourceConsumption(ResourceScope.Machine)] //For MetadataArtifactLoader.CreateCompositeFromFilePaths method call but we do not create the file paths in this method
        public StoreItemCollection(params string[] filePaths)
            : base(DataSpace.SSpace)
        {
            EntityUtil.CheckArgumentNull(filePaths, "filePaths");
            IEnumerable <string> enumerableFilePaths = filePaths;

            EntityUtil.CheckArgumentEmpty(ref enumerableFilePaths, Strings.StoreItemCollectionMustHaveOneArtifact, "filePaths");

            // Wrap the file paths in instances of the MetadataArtifactLoader class, which provides
            // an abstraction and a uniform interface over a diverse set of metadata artifacts.
            //
            MetadataArtifactLoader composite = null;
            List <XmlReader>       readers   = null;

            try
            {
                composite = MetadataArtifactLoader.CreateCompositeFromFilePaths(enumerableFilePaths, XmlConstants.SSpaceSchemaExtension);
                readers   = composite.CreateReaders(DataSpace.SSpace);
                IEnumerable <XmlReader> ieReaders = readers.AsEnumerable();
                EntityUtil.CheckArgumentEmpty(ref ieReaders, Strings.StoreItemCollectionMustHaveOneArtifact, "filePaths");

                this.Init(readers,
                          composite.GetPaths(DataSpace.SSpace), true,
                          out _providerManifest,
                          out _providerFactory,
                          out _providerManifestToken,
                          out _cachedCTypeFunction);
            }
            finally
            {
                if (readers != null)
                {
                    Helper.DisposeXmlReaders(readers);
                }
            }
        }
Esempio n. 21
0
        [ResourceConsumption(ResourceScope.Machine)] //For MetadataArtifactLoader.Create method call. But the path is not created in this method.
        internal static List <MetadataArtifactLoader> SplitPaths(string paths)
        {
            Debug.Assert(!string.IsNullOrEmpty(paths), "paths cannot be empty or null");

            string[] results;

            // This is the registry of all URIs in the global collection.
            HashSet <string> uriRegistry = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            List <MetadataArtifactLoader> loaders = new List <MetadataArtifactLoader>();

            // If the argument contains one or more occurrences of the macro '|DataDirectory|', we
            // pull those paths out so that we don't lose them in the string-splitting logic below.
            // Note that the macro '|DataDirectory|' cannot have any whitespace between the pipe
            // symbols and the macro name. Also note that the macro must appear at the beginning of
            // a path (else we will eventually fail with an invalid path exception, because in that
            // case the macro is not expanded). If a real/physical folder named 'DataDirectory' needs
            // to be included in the metadata path, whitespace should be used on either or both sides
            // of the name.
            //
            List <string> dataDirPaths = new List <string>();

            int indexStart = paths.IndexOf(MetadataCache.s_dataDirectory, StringComparison.OrdinalIgnoreCase);

            while (indexStart != -1)
            {
                int prevSeparatorIndex = indexStart == 0 ? -1 : paths.LastIndexOf(
                    MetadataCache.s_metadataPathSeparator,
                    indexStart - 1,                                             // start looking here
                    StringComparison.Ordinal
                    );

                int macroPathBeginIndex = prevSeparatorIndex + 1;

                // The '|DataDirectory|' macro is composable, so identify the complete path, like
                // '|DataDirectory|\item1\item2'. If the macro appears anywhere other than at the
                // beginning, splice out the entire path, e.g. 'C:\item1\|DataDirectory|\item2'. In this
                // latter case the macro will not be expanded, and downstream code will throw an exception.
                //
                int indexEnd = paths.IndexOf(MetadataCache.s_metadataPathSeparator,
                                             indexStart + MetadataCache.s_dataDirectory.Length,
                                             StringComparison.Ordinal);
                if (indexEnd == -1)
                {
                    dataDirPaths.Add(paths.Substring(macroPathBeginIndex));
                    paths = paths.Remove(macroPathBeginIndex);   // update the concatenated list of paths
                    break;
                }

                dataDirPaths.Add(paths.Substring(macroPathBeginIndex, indexEnd - macroPathBeginIndex));

                // Update the concatenated list of paths by removing the one containing the macro.
                //
                paths      = paths.Remove(macroPathBeginIndex, indexEnd - macroPathBeginIndex);
                indexStart = paths.IndexOf(MetadataCache.s_dataDirectory, StringComparison.OrdinalIgnoreCase);
            }

            // Split the string on the separator and remove all spaces around each parameter value
            results = paths.Split(new string[] { MetadataCache.s_metadataPathSeparator }, StringSplitOptions.RemoveEmptyEntries);

            // Now that the non-macro paths have been identified, merge the paths containing the macro
            // into the complete list.
            //
            if (dataDirPaths.Count > 0)
            {
                dataDirPaths.AddRange(results);
                results = dataDirPaths.ToArray();
            }

            for (int i = 0; i < results.Length; i++)
            {
                // Trim out all the spaces for this parameter and add it only if it's not blank
                results[i] = results[i].Trim();
                if (results[i].Length > 0)
                {
                    loaders.Add(MetadataArtifactLoader.Create(
                                    results[i],
                                    MetadataArtifactLoader.ExtensionCheck.All,  // validate the extension against all acceptable values
                                    null,
                                    uriRegistry
                                    ));
                }
            }

            return(loaders);
        }
Esempio n. 22
0
 public EdmItemCollectionLoader(MetadataArtifactLoader loader)
 {
     Debug.Assert(loader != null, "loader must never be null");
     _loader = loader;
 }
Esempio n. 23
0
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //Fir SplitPaths call and we pick the file names from class variable.
        internal MetadataWorkspace GetMetadataWorkspace(bool initializeAllCollections)
        {
            Debug.Assert(_metadataWorkspace != null || _effectiveConnectionOptions != null, "The effective connection options is null, which should never be");
            if (_metadataWorkspace == null ||
                (initializeAllCollections && !_metadataWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace)))
            {
                // This lock is to ensure that the connection string and the metadata workspace are in a consistent state, that is, you
                // don't get a metadata workspace not matching what's described by the connection string
                lock (_connectionStringLock)
                {
                    EdmItemCollection edmItemCollection = null;
                    if (_metadataWorkspace == null)
                    {
                        MetadataWorkspace workspace = new MetadataWorkspace();
                        List<MetadataArtifactLoader> loaders = new List<MetadataArtifactLoader>();
                        string paths = _effectiveConnectionOptions[EntityConnectionStringBuilder.MetadataParameterName];

                        if (!string.IsNullOrEmpty(paths))
                        {
                            loaders = MetadataCache.GetOrCreateMetdataArtifactLoader(paths);
                            
                            if(!ShouldRecalculateMetadataArtifactLoader(loaders))
                            {
                                _artifactLoader = MetadataArtifactLoader.Create(loaders);
                            }
                            else
                            {
                                // the loaders contains folders that might get updated during runtime, so we have to recalculate the loaders again
                                _artifactLoader = MetadataArtifactLoader.Create(MetadataCache.SplitPaths(paths));
                            }
                        }
                        else
                        {
                            _artifactLoader = MetadataArtifactLoader.Create(loaders);
                        }

                        edmItemCollection = LoadEdmItemCollection(workspace, _artifactLoader);
                        _metadataWorkspace = workspace;
                    }
                    else
                    {
                        edmItemCollection = (EdmItemCollection)_metadataWorkspace.GetItemCollection(DataSpace.CSpace);
                    }

                    if (initializeAllCollections && !_metadataWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace))
                    {
                        LoadStoreItemCollections(_metadataWorkspace, _storeConnection, _providerFactory, _effectiveConnectionOptions, edmItemCollection, _artifactLoader);
                        _artifactLoader = null;
                        _initialized = true;
                    }
                }
            }

            return _metadataWorkspace;
        }
Esempio n. 24
0
        private static EdmItemCollection LoadEdmItemCollection(MetadataWorkspace workspace, MetadataArtifactLoader artifactLoader)
        {
            // Build a string as the key and look up the MetadataCache for a match
            string edmCacheKey = CreateMetadataCacheKey(artifactLoader.GetOriginalPaths(DataSpace.CSpace), null, null);

            // Check the MetadataCache for an entry with this key
            object entryToken;
            EdmItemCollection edmItemCollection = MetadataCache.GetOrCreateEdmItemCollection(edmCacheKey,
                                                                                        artifactLoader,
                                                                                        out entryToken);
            workspace.RegisterItemCollection(edmItemCollection);

            // Adding the edm metadata entry token to the workspace, to make sure that this token remains alive till workspace is alive
            workspace.AddMetadataEntryToken(entryToken);

            return edmItemCollection;
        }
Esempio n. 25
0
        private void GenerateCodeCommon(MetadataArtifactLoader sourceLoader, 
            List<MetadataArtifactLoader> loaders,
            LazyTextWriterCreator target,
            string sourceEdmSchemaFilePath,
            string targetFilePath,
            bool closeReaders,
            List<EdmSchemaError> errors)
        {
            MetadataArtifactLoaderComposite composite = new MetadataArtifactLoaderComposite(loaders);
            
            // create the schema manager from the xml readers
            Dictionary<MetadataArtifactLoader, XmlReader> readerSourceMap = new Dictionary<MetadataArtifactLoader, XmlReader>();
            IList<Schema> schemas;
            List<XmlReader> readers = composite.GetReaders(readerSourceMap);

            try
            {
                IList<EdmSchemaError> schemaManagerErrors =
                    SchemaManager.ParseAndValidate(readers,
                        composite.GetPaths(),
                        SchemaDataModelOption.EntityDataModel,
                        EdmProviderManifest.Instance,
                        out schemas);
                errors.AddRange(schemaManagerErrors);
            }
            finally
            {
                if (closeReaders)
                {
                    MetadataUtil.DisposeXmlReaders(readers);
                }
            }
            ThrowOnAnyNonWarningErrors(errors);
            Debug.Assert(readerSourceMap.ContainsKey(sourceLoader), "the source loader didn't produce any of the xml readers...");
            XmlReader sourceReader = readerSourceMap[sourceLoader];


            // use the index of the "source" xml reader as the index of the "source" schema
            Debug.Assert(readers.Contains(sourceReader), "the source reader is not in the list of readers");
            int index = readers.IndexOf(sourceReader);
            Debug.Assert(index >= 0, "couldn't find the source reader in the list of readers");

            Debug.Assert(readers.Count == schemas.Count, "We have a different number of readers than schemas");
            Schema sourceSchema = schemas[index];
            Debug.Assert(sourceSchema != null, "sourceSchema is null");

            // create the EdmItemCollection from the schemas
            EdmItemCollection itemCollection = new EdmItemCollection(schemas);
            if (EntityFrameworkVersionsUtil.ConvertToVersion(itemCollection.EdmVersion) >= EntityFrameworkVersions.Version2)
            {
                throw EDesignUtil.InvalidOperation(Strings.TargetEntityFrameworkVersionToNewForEntityClassGenerator);  
            }

            // generate code
            ClientApiGenerator generator = new ClientApiGenerator(sourceSchema, itemCollection, this, errors);
            generator.GenerateCode(target, targetFilePath);
        }
Esempio n. 26
0
        private static void LoadStoreItemCollections(MetadataWorkspace workspace,
                                                     DbConnection storeConnection,
                                                     DbProviderFactory factory,
                                                     DbConnectionOptions connectionOptions,
                                                     EdmItemCollection edmItemCollection,
                                                     MetadataArtifactLoader artifactLoader)                                                     
        {
            Debug.Assert(workspace.IsItemCollectionAlreadyRegistered(DataSpace.CSpace), "C-Space must be loaded before loading S or C-S space");
                        
            // The provider connection string is optional; if it has not been specified,
            // we pick up the store's connection string.
            //
            string providerConnectionString = connectionOptions[EntityConnectionStringBuilder.ProviderConnectionStringParameterName];
            if (string.IsNullOrEmpty(providerConnectionString) && (storeConnection != null))
            {
                providerConnectionString = storeConnection.ConnectionString;
            }

            // Build a string as the key and look up the MetadataCache for a match
            string storeCacheKey = CreateMetadataCacheKey(artifactLoader.GetOriginalPaths(),
                                                          connectionOptions[EntityConnectionStringBuilder.ProviderParameterName],
                                                          providerConnectionString);

            // Load store metadata.
            object entryToken;
            StorageMappingItemCollection mappingCollection =
                MetadataCache.GetOrCreateStoreAndMappingItemCollections(storeCacheKey,
                                                                     artifactLoader,
                                                                     edmItemCollection,
                                                                     out entryToken);

            workspace.RegisterItemCollection(mappingCollection.StoreItemCollection);
            workspace.RegisterItemCollection(mappingCollection);

            // Adding the store metadata entry token to the workspace
            workspace.AddMetadataEntryToken(entryToken);
        }