public void InitialiseEntityModel(ArchAngel.Providers.EntityModel.ProviderInfo providerInfo, PreGenerationData data)
        {
            providerInfo.MappingSet.CodeParseResults = null;
            // Clear the current mapped class.
            providerInfo.MappingSet.EntitySet.Entities.ForEach(e => e.MappedClass = null);

            // Find the csproj file we are going to use
            string filename;
            var csprojDocument = GetCSProjDocument(data, out filename);

            if (csprojDocument == null)
                return;

            CSProjFile csproj = new CSProjFile(csprojDocument, filename);
            var hbmFiles = ProjectLoader.GetHBMFilesFromCSProj(csproj, fileController);

            // Load HBMs
            foreach (string hbmFilePath in hbmFiles)
            {
                if (!File.Exists(hbmFilePath))
                    throw new FileNotFoundException(string.Format("A file is defined is your csproj file [{0}], but it cannot be found: [{1}]", filename, hbmFilePath), hbmFilePath);
            }
            var mappings = hbmFiles.Select(f => MappingFiles.Version_2_2.Utility.Open(f)).ToList();

            // Parse the CSharp files
            var csharpFiles = ProjectLoader.GetCSharpFilesFromCSProj(csproj, fileController);
            var parseResults = ParseResults.ParseCSharpFiles(csharpFiles);

            providerInfo.MappingSet.CodeParseResults = parseResults;

            // Clear the current mapped class.
            providerInfo.MappingSet.EntitySet.Entities.ForEach(e => e.MappedClass = null);

            // Map the Entity objects to the parsed Class
            var entities = providerInfo.MappingSet.EntitySet.Entities.ToDictionary(e => e.Name);

            foreach (var hm in mappings)
            {
                foreach (var hClass in hm.Classes())
                {
                    var fullClassName = HibernateMappingHelper.ResolveFullClassName(hClass, hm);
                    var shortClassName = HibernateMappingHelper.ResolveShortClassName(hClass, hm);

                    // try find the entity
                    Entity entity;
                    if (entities.TryGetValue(shortClassName, out entity))
                    {
                        // try find class in parse results
                        var parsedClass = parseResults.FindClass(fullClassName, entity.Properties.Select(p => p.Name).ToList());
                        entity.MappedClass = parsedClass;
                    }
                    else
                    {
                        Log.InfoFormat("Could not find entity for class named {0} in the NHibernate project on disk.", shortClassName);
                    }
                }
            }
            // Now, try to map entities that haven't been found yet
            foreach (var entity in entities.Select(v => v.Value).Where(e => e.MappedClass == null))
            {
                string entityName = entity.Name;
                // try find class in parse results
                var parsedClass = parseResults.FindClass(entityName, entity.Properties.Select(p => p.Name).ToList());
                entity.MappedClass = parsedClass;
            }
        }
Ejemplo n.º 2
0
        private bool FluentCompiledAssemblyFound()
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(File.ReadAllText(tbProjectLocation.Text));
            CSProjFile csProjFile = new CSProjFile(doc, tbProjectLocation.Text);

            string tempFluentPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Visual NHibernate" + Path.DirectorySeparatorChar + "Temp" + Path.DirectorySeparatorChar + "FluentTemp");

            try
            {
                var fluentHbmFiles = NHibernateHelper.ProjectLoader.GetHBMFilesForFluentFromCSProj(csProjFile, tempFluentPath);
            }
            catch (FluentNHibernateCompiledAssemblyMissingException e)
            {
                return false;
            }
            return true;
        }
Ejemplo n.º 3
0
        private NHConfigFile GetNhConfigFileFromCsprojFile(string filepath)
        {
            nhConfigFile = null;

            if (!File.Exists(filepath))
                return null;

            try
            {
                // Check whether we can find a config file
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(File.ReadAllText(filepath));
                CSProjFile csProjFile = new CSProjFile(doc, tbProjectLocation.Text);
                Slyce.Common.FileController fileController = new FileController();
                nhConfigFile = ProjectLoader.GetNhConfigFile(csProjFile, fileController);
            }
            catch
            {
                // Do nothing. We are probably trying to process a non-XML file.
            }
            return nhConfigFile;
        }
Ejemplo n.º 4
0
 public IEnumerable<string> GetPossibleNHibernateConfigFilesFromCSProj(CSProjFile csproj)
 {
     return GetPossibleNHibernateConfigFilesFromCSProj(csproj, fileController);
 }
Ejemplo n.º 5
0
        public LoadResult LoadEntityModelFromCSProj(string csprojFilePath, NHConfigFile nhConfigFile)
        {
            _progress.SetCurrentState("Loading Entities From Visual Studio Project", ProgressState.Normal);

            EntityLoader entityLoader = new EntityLoader(new FileController());

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(fileController.ReadAllText(csprojFilePath));
            CSProjFile csProjFile = new CSProjFile(doc, csprojFilePath);
            var hbmFiles = GetHBMFilesFromCSProj(csProjFile);

            if (IsFluentProject(csProjFile))
            {
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("UseFluentNHibernate", true);
                string tempFluentPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Visual NHibernate" + Path.DirectorySeparatorChar + "Temp" + Path.DirectorySeparatorChar + "FluentTemp");
                var fluentHbmFiles = GetHBMFilesForFluentFromCSProj(csProjFile, tempFluentPath);
                // Combine the actual HBM files with the ones derived from FluentNH
                hbmFiles = hbmFiles.Union(fluentHbmFiles);
            }
            else
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("UseFluentNHibernate", false);

            var csFiles = GetCSharpFilesFromCSProj(doc, csprojFilePath);
            var nhvFiles = GetNHVFilesFromCSProj(doc, csprojFilePath);

            //NHConfigFile nhConfigFile = GetNhConfigFile(csProjFile, fileController);

            var databaseConnector = nhConfigFile == null ? null : nhConfigFile.DatabaseConnector;

            //////// GFH
            // We need to fetch ALL tables, because HBM mappings don't include association tables, or at least it's difficult to find them.
            List<SchemaData> tablesToFetch = null;// entityLoader.GetTablesFromHbmFiles(hbmFiles);

            IDatabaseLoader loader = null;
            IDatabase database = null;

            if (databaseConnector != null)
                database = GetDatabase(databaseConnector, out loader, tablesToFetch);

            _progress.SetCurrentState("Parsing your existing Model Project", ProgressState.Normal);
            var parseResults = ParseResults.ParseCSharpFiles(csFiles);

            _progress.SetCurrentState("Loading Mapping Information From NHibernate Mapping Files", ProgressState.Normal);
            var mappingSet = entityLoader.GetEntities(hbmFiles, parseResults, database);
            entityLoader.ApplyConstraints(mappingSet, nhvFiles, parseResults);

            #region Create References

            // Get a set of all Guids for tables that we will want to create references from
            HashSet<Guid> existingTables = new HashSet<Guid>(database.Tables.Select(t => t.InternalIdentifier));

            foreach (var mappedTable in mappingSet.Mappings.Select(m => m.FromTable))
                existingTables.Add(mappedTable.InternalIdentifier);

            HashSet<Guid> processedRelationships = new HashSet<Guid>();
            foreach (var table in database.Tables)
            {
                foreach (var directedRel in table.DirectedRelationships)
                {
                    var relationship = directedRel.Relationship;

                    if (processedRelationships.Contains(relationship.InternalIdentifier))
                        continue; // Skip relationships that have already been handled.
                    if (relationship.MappedReferences().Any())
                        continue; // Skip relationships that have been mapped by the user.
                    if (existingTables.Contains(directedRel.ToTable.InternalIdentifier) == false)
                        continue; // Skip relationships that have tables that have no mapped Entity

                    if (relationship.PrimaryTable.MappedEntities().FirstOrDefault() == null ||
                        relationship.ForeignTable.MappedEntities().FirstOrDefault() == null)
                    {
                        continue;
                    }
                    ArchAngel.Providers.EntityModel.Controller.MappingLayer.MappingProcessor.ProcessRelationshipInternal(mappingSet, relationship, new ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor());
                    processedRelationships.Add(relationship.InternalIdentifier);
                }
            }
            #endregion

            foreach (var entity in mappingSet.EntitySet.Entities)
                foreach (var reference in entity.References)
                    if (!mappingSet.EntitySet.References.Contains(reference))
                        mappingSet.EntitySet.AddReference(reference);

            LoadResult result = new LoadResult();
            result.MappingSet = mappingSet;
            result.DatabaseLoader = loader;
            result.NhConfigFile = nhConfigFile;
            result.CsProjFile = csProjFile;
            return result;
        }
Ejemplo n.º 6
0
 public IEnumerable<string> GetHBMFilesFromCSProj(CSProjFile csproj)
 {
     return GetHBMFilesFromCSProj(csproj, fileController);
 }
Ejemplo n.º 7
0
 public NHConfigFile GetNhConfigFile(CSProjFile csproj)
 {
     return GetNhConfigFile(csproj, fileController);
 }
Ejemplo n.º 8
0
 public static bool IsFluentProject(string csProjFilePath)
 {
     XmlDocument doc = new XmlDocument();
     doc.LoadXml(File.ReadAllText(csProjFilePath));
     CSProjFile csProjFile = new CSProjFile(doc, csProjFilePath);
     return IsFluentProject(csProjFile);
 }
Ejemplo n.º 9
0
        public static bool IsFluentProject(CSProjFile csProjFile)
        {
            var referencedFiles = csProjFile.GetReferencedAssemblies();

            foreach (string file in referencedFiles)
            {
                if (file.ToLower().EndsWith("fluentnhibernate.dll"))
                    return true;
            }
            return false;
        }
Ejemplo n.º 10
0
 public static IEnumerable<string> GetPossibleNHibernateConfigFilesFromCSProj(CSProjFile csproj, IFileController controller)
 {
     return csproj
         .GetEmbeddedResources(f => f.EndsWith(".cfg.xml", StringComparison.OrdinalIgnoreCase))
         .Concat(csproj.GetFilesMarkedNone(f => f.EndsWith(".cfg.xml", StringComparison.OrdinalIgnoreCase)))
         .Concat(csproj.GetContentFiles(f => f.EndsWith(".cfg.xml", StringComparison.OrdinalIgnoreCase)))
         .Concat(csproj.GetResourceFiles(f => f.EndsWith(".cfg.xml", StringComparison.OrdinalIgnoreCase)))
         .Concat(csproj.GetFilesMarkedNone(f => f.EndsWith(".config", StringComparison.OrdinalIgnoreCase)))
         .Select(f => controller.ToAbsolutePath(f, csproj.FilePath))
         .ToList();
 }
Ejemplo n.º 11
0
 public static IEnumerable<string> GetNHVFilesFromCSProj(CSProjFile csproj, string csprojPath, IFileController controller)
 {
     return csproj
         .GetEmbeddedResources(f => f.EndsWith(".nhv.xml", StringComparison.OrdinalIgnoreCase))
         .Select(f => controller.ToAbsolutePath(f, csprojPath))
         .ToList();
 }
Ejemplo n.º 12
0
        public static NHConfigFile GetNhConfigFile(CSProjFile csproj, IFileController fileController)
        {
            //if (string.IsNullOrEmpty(csprojPath) || !File.Exists(csprojPath))
            //    return null;

            NHConfigFile nhConfigFile = null;
            var configFiles = GetPossibleNHibernateConfigFilesFromCSProj(csproj, fileController);

            string cfgXmlFile = null;
            bool invalidSchemaFound = false;

            foreach (var configFilePath in configFiles)
            {
                if (File.Exists(configFilePath))
                {
                    // Test if it is an NHibernate file.
                    nhConfigFile = GetConfigFromXmlFile(ref cfgXmlFile, ref invalidSchemaFound, configFilePath);

                    if (nhConfigFile != null)
                        break;
                }
            }
            if (cfgXmlFile == null &&
                !(invalidSchemaFound || configFiles.Contains("hibernate.cfg.xml")))
            {
                // We can't find a valid config file in the project - it might exist in
                // another project, so ask the user to locate it.
                string filepath = "";
                return null;
            }
            if (cfgXmlFile == null)
            {
                if (invalidSchemaFound)
                {
                    throw new NHibernateConfigException("Your NHibernate Configuration file uses an unsupported version of the schema. We only support NHibernate Version 2.2");
                }
                if (configFiles.Contains("hibernate.cfg.xml"))
                {
                    throw new NHConfigFileMissingException("Your NHibernate configuration file does not validate against the NHibernate Configuration Schema version 2.2");
                }
                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                foreach (var location in configFiles)
                {
                    sb.AppendLine(location);
                }
                string message = string.Format("Could not find the NHibernate configuration file in your project. Locations searched:{0}{1}", Environment.NewLine, sb);
                return null;
                //throw new NHConfigFileMissingException(message);
            }
            return nhConfigFile;
        }
Ejemplo n.º 13
0
        public static IEnumerable<string> GetHBMFilesForFluentFromCSProj(CSProjFile csproj, string outputPath)
        {
            string assemblyName = csproj.GetAssemblyName();
            IEnumerable<string> outputPaths = csproj.GetOutputPaths();
            DateTime latestAssemblyDate = new DateTime(1900, 1, 1);
            string latestAssembly = "";

            foreach (string folder in outputPaths)
            {
                string assemblyPath = Path.Combine(folder, assemblyName);

                if (File.Exists(assemblyPath))
                {
                    DateTime lastWriteTime = File.GetLastWriteTimeUtc(assemblyPath);

                    if (lastWriteTime > latestAssemblyDate)
                    {
                        latestAssemblyDate = lastWriteTime;
                        latestAssembly = assemblyPath;
                    }
                }
            }
            if (string.IsNullOrEmpty(latestAssembly))
                throw new FluentNHibernateCompiledAssemblyMissingException("No compiled assembly found. A compiled assembly is required for Fluent NHibernate. Please recompile your project.");

            System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(latestAssembly);
            FluentCompileLatestAssemblyDir = Path.GetDirectoryName(latestAssembly);

            try
            {
                assembly.ModuleResolve += new System.Reflection.ModuleResolveEventHandler(assembly_ModuleResolve);
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

                if (!Directory.Exists(outputPath))
                    Directory.CreateDirectory(outputPath);

                //var sessionFactory = FluentNHibernate.Cfg.Fluently.Configure()
                //                  .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
                //                    .ConnectionString("Data Source=STN_DEV;Initial Catalog=FNHProviderDB;Integrated Security=SSPI;")
                //                  )
                //                  .Mappings(m => m.FluentMappings.AddFromAssembly(assembly).ExportTo(outputPath))
                //                  .BuildConfiguration();

                AutoPersistenceModel mappings = new AutoPersistenceModel();
                mappings.AddMappingsFromAssembly(assembly);
                mappings.BuildMappings();
                mappings.WriteMappingsTo(outputPath);

                return Directory.GetFiles(outputPath).ToList();
            }
            finally
            {
                assembly.ModuleResolve -= assembly_ModuleResolve;
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomain_ReflectionOnlyAssemblyResolve;
            }
        }
Ejemplo n.º 14
0
 public static IEnumerable<string> GetCSharpFilesFromCSProj(CSProjFile csproj, IFileController controller)
 {
     return csproj
         .GetFilesMarkedCompile(f => f.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
         .Select(f => controller.ToAbsolutePath(f, csproj.FilePath))
         .ToList();
 }