Esempio n. 1
0
        /// <summary>
        /// Populates the provider with the saved data from the folder that contains the Provider Data folders.
        /// Don't use this method if you could use PopulateProviderFromProjectFile. It has the logic for finding
        /// the right folder from the projectFile.
        /// For example, we would be expecting to be given the full path to Project Files under this scheme:
        ///
        /// Project Files
        /// |--> ExampleProvider_data
        ///      |--> somefile.xml
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="folder"></param>
        public static void PopulateProvider(ProviderInfo provider, string folder)
        {
            string providerFolder = folder.PathSlash(provider.Assembly.GetName().Name.Replace(".", "_") + "_data");

            if (Directory.Exists(providerFolder))
            {
                provider.Open(providerFolder);
            }
            else if (provider.Assembly.FullName.IndexOf("ArchAngel.Providers.Database") >= 0)
            {
                // Check for a non-zipped version of 'provider_database.settings'. This is for backwards compatibility with older versions of ArchAngel.
                string dbFile = folder.PathSlash("provider_database.settings");
                string zipFile = folder.PathSlash("provider_database_data.zip");
                string tempFolder = GetProviderTempFolder(provider);

                if (File.Exists(zipFile))
                {
                    Utility.UnzipFile(zipFile, tempFolder);
                    provider.Open(tempFolder);
                }
                else if (File.Exists(dbFile))
                {
                    File.Copy(dbFile, tempFolder.PathSlash(Path.GetFileName(dbFile)));
                    provider.Open(tempFolder);
                }
                // Delete the temp folder
                Utility.DeleteDirectoryBrute(tempFolder);
            }
        }
Esempio n. 2
0
 public static void PreGenerationModelInitialisation(ArchAngel.Interfaces.ProviderInfo provider, PreGenerationData data)
 {
     if (provider == null)
     {
         return;
     }
     if (provider is ArchAngel.Providers.EntityModel.ProviderInfo)
     {
         new EntityModelPreprocessor((IFileController) new FileController()).InitialiseEntityModel((ArchAngel.Providers.EntityModel.ProviderInfo)provider, data);
     }
     else
     {
         if (!(provider is ArchAngel.NHibernateHelper.ProviderInfo))
         {
             return;
         }
         new NHibernateProjectPreprocessor((IFileController) new FileController()).InitialiseNHibernateProject((ArchAngel.NHibernateHelper.ProviderInfo)provider, data);
     }
 }
Esempio n. 3
0
        public override void RunCustomNewProjectLogic(ArchAngel.Interfaces.ProviderInfo theProviderInfo, IUserInteractor userInteractor)
        {
            NHibernateHelper.ProviderInfo providerInfo = (NHibernateHelper.ProviderInfo)theProviderInfo;
            providerInfo.Clear();
            providerInfo.NhConfigFile = this.NhConfigFile;
            userInteractor.ShowWaitScreen("Loading from your existing NHibernate project");
            // Run this in its own thread
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork
                += (s, args) =>
                {
                try
                {
                    var loader = new ProjectLoader(new FileController(), new IUserInteractorProgressUpdatorAdapter(userInteractor), userInteractor);
                    var result = loader.LoadEntityModelFromCSProj(Filename, this.NhConfigFile);
                    args.Result = new RunResult {
                        MappingSet = result.MappingSet, DatabaseLoader = result.DatabaseLoader, NhConfigFile = result.NhConfigFile, CsProjFile = result.CsProjFile
                    };
                }
                catch (NHibernateLoaderException e)
                {
                    //var sb = new StringBuilder();
                    //sb.Append("The HBM files [").Append(e.Filenames).AppendLine(
                    //    "] could not be loaded due to the following errors:");
                    //e.Errors.ForEach(err => sb.AppendLine(err.Message));
                    //sb.AppendLine("Please send this file to [email protected] so we can make our HBM Loader better.");

                    args.Result = new RunResult {
                        ErrorOccurred = true, Exception = e
                    };
                }
                catch (Exception e)
                {
                    throw new NHibernateLoaderException(e.Message + Environment.NewLine + e.StackTrace, null, null);
                }
                };

            worker.RunWorkerCompleted
                += (s, args) =>
                {
                if (args.Error != null)
                {
                    userInteractor.RemoveWaitScreen();
                    providerInfo.EntityProviderInfo.MappingSet = new MappingSetImpl();
                    throw new Exception("An error occurred in RunCustomNewProjectLogic. The inner exception is: " + args.Error.StackTrace, args.Error);
                    //System.Windows.Forms.Clipboard.SetText(args.Error.StackTrace);
                    //userInteractor.ShowError("An Error Occurred", args.Error.Message + Environment.NewLine + Environment.NewLine + "The stacktrace has been copied to the clipboard. Please email to [email protected]");
                    //providerInfo.EntityProviderInfo.MappingSet = new MappingSetImpl();
                }
                else
                {
                    var result = (RunResult)args.Result;
                    if (result.ErrorOccurred)
                    {
                        userInteractor.RemoveWaitScreen();
                        providerInfo.EntityProviderInfo.MappingSet = new MappingSetImpl();

                        string errorMessage = string.Format("Unsupported elements or Schema Validation Errors occurred. Please submit this error.\nFiles: {0}", result.Exception.Filenames);
                        throw new Exception(errorMessage, result.Exception);
                        //var form = new NHibernateHBMLoadErrorView();
                        //form.Title = "Unsupported elements or Schema Validation Errors occurred";
                        //form.NameOfFileWithError = result.Exception.Filename;
                        //form.SetErrors(result.Exception.Errors);

                        //userInteractor.ShowDialog(form);
                    }
                    else
                    {
                        // Set the MappingSet to the result of our work.
                        providerInfo.EntityProviderInfo.MappingSet = result.MappingSet;
                        providerInfo.NhConfigFile = result.NhConfigFile;
                        providerInfo.CsProjFile   = result.CsProjFile;

                        if (!string.IsNullOrEmpty(providerInfo.CsProjFile.GetProjectGuid()))
                        {
                            ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("ProjectGuid", providerInfo.CsProjFile.GetProjectGuid());
                        }

                        ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("CacheProviderClass", providerInfo.NhConfigFile.cache_provider_class);

                        // Then run the validation rules
                        userInteractor.UpdateWaitScreen("Runnng Model Validation");
                        //var rulesEngine = new ValidationRulesEngine(result.MappingSet);
                        //var database = result.DatabaseLoader.LoadDatabase();
                        //rulesEngine.AddModule(new NHibernateProjectLoaderModule(database));
                        providerInfo.EntityProviderInfo.RunValidationRules();                                        //rulesEngine);

                        userInteractor.RemoveWaitScreen();
                    }
                }
                };

            worker.RunWorkerAsync();
        }
Esempio n. 4
0
        public override void RunCustomNewProjectLogic(ArchAngel.Interfaces.ProviderInfo theProviderInfo, IUserInteractor userInteractor)
        {
            //if (theProviderInfo is ArchAngel.Providers.EntityModel.ProviderInfo)
            //{
            //    ArchAngel.Providers.EntityModel.ProviderInfo providerInfo = (ArchAngel.Providers.EntityModel.ProviderInfo)theProviderInfo;
            //    providerInfo.Clear();
            //    return;
            //}

            try
            {
                log.Debug("Loading project...");
                userInteractor.UpdateWaitScreen("Loading project...");

                NHibernateHelper.ProviderInfo providerInfo = (NHibernateHelper.ProviderInfo)theProviderInfo;
                providerInfo.Clear();

                log.Debug("Loading database...");
                Database          database    = DatabaseLoader.LoadDatabase(DatabaseLoader.DatabaseObjectsToFetch, null);
                DatabaseProcessor dbProcessor = new DatabaseProcessor();
                dbProcessor.LogErrors = true;
                log.Debug("Creating relationships...");
                dbProcessor.CreateRelationships(database);

                if (dbProcessor.Errors.Count > 0)
                {
                    log.Debug("Database errors exist..." + dbProcessor.Errors.Count.ToString());
                    UI.FormErrors form = new UI.FormErrors("<b><font color='Red'>Note:</font></b> Database problems exist. Please <b>fix</b> these problems (or <b>omit the tables</b> in question) before trying again.", dbProcessor.Errors);
                    form.ShowDialog();
                    return;
                }
                log.Debug("Creating 1 to 1 mappings...");
                var mappingSet = new MappingProcessor(new OneToOneEntityProcessor())
                                 .CreateOneToOneMapping(database, this.TablePrefixes, this.ColumnPrefixes, this.TableSuffixes, this.ColumnSuffixes);

                foreach (var entity in mappingSet.EntitySet.Entities)
                {
                    ArchAngel.Interfaces.ProjectOptions.ModelScripts.Scripts.ExistingPropertyNames = new List <string>();

                    foreach (Property prop in entity.Properties)
                    {
                        IColumn mappedCol = prop.MappedColumn();

                        ArchAngel.Interfaces.Scripting.NHibernate.Model.IColumn scriptCol = new Interfaces.Scripting.NHibernate.Model.IColumn()
                        {
                            IsNullable = mappedCol.IsNullable,
                            //IsText =
                            Length       = mappedCol.Size,
                            Name         = mappedCol.Name,
                            ScriptObject = mappedCol,
                            Type         = mappedCol.OriginalDataType
                        };
                        prop.Name = ArchAngel.Interfaces.ProjectOptions.ModelScripts.Scripts.GetPropertyName(scriptCol);
                    }
                }
                providerInfo.EntityProviderInfo.MappingSet = mappingSet;
                /////////////////////////////////
                providerInfo.EntityProviderInfo.Engine.AddModule(new NHibernateProjectLoaderModule(database));
                // Then run the validation rules
                log.Debug("Validating model...");
                userInteractor.UpdateWaitScreen("Validating model...");
                //var rulesEngine = new ValidationRulesEngine(mappingSet);
                //rulesEngine.AddModule(new NHibernateProjectLoaderModule(database));
                log.Debug("Running validation rules...");
                providerInfo.EntityProviderInfo.RunValidationRules();                //rulesEngine);
            }
            //catch (Exception ex)
            //{
            //    MessageBox.
            //}
            finally
            {
                log.Debug("Removing wait screen...");
                userInteractor.RemoveWaitScreen();
            }
        }
 private void SetupProvider(ProviderInfo providerMock)
 {
     ProviderInfo provider;
     Expect
         .Call(projectInfo.GetIteratorTypeFromProviders("Iterator", out provider))
         .Return(typeof(IScriptBaseObject)).OutRef(providerMock)
         .Repeat.Any();
     Expect.Call(projectInfo.GetIteratorTypeFromProviders("Iterator"))
         .Return(typeof(IScriptBaseObject))
         .Repeat.Any();
      Expect.Call(providerMock.GetAllObjectsOfType(null))
          .IgnoreArguments()
         .Return(new System.Collections.Generic.List<IScriptBaseObject>())
         .Repeat.Any();
 }
Esempio n. 6
0
        public void CallPreGenerationInitialisationFunction(ProviderInfo provider, PreGenerationData data)
        {
            MethodInfo method = _TemplateGenInstance.GetType().GetMethod(TemplateHelper.PreGenerationModelProcessingFunctionName);

            if (method == null) return;

            var parameters = new object[] { provider, data };
            method.Invoke(_TemplateGenInstance, parameters);
        }
Esempio n. 7
0
 public abstract void RunCustomNewProjectLogic(ArchAngel.Interfaces.ProviderInfo providerInfo, IUserInteractor userInteractor);
Esempio n. 8
0
        public int WriteFiles(
			ProjectFileTreeNode parentNode,
			ArchAngel.Interfaces.Scripting.NHibernate.Model.IProject project,
			string targetFolder,
			ArchAngel.Interfaces.Template.TemplateProject templateProject,
			out List<FilenameInfo> duplicateFiles)
        {
            if (!Directory.Exists(targetFolder))
                throw new FileNotFoundException("Output folder doesn't exist: " + targetFolder, targetFolder);

            ////////////////////////////////////////
            TargetFolder = targetFolder;

            SharedData.IsBusyGenerating = true;
            SharedData.CurrentProject.StartNewFileGenerationRun();

            // Reset the Template before the File name validation run.
            _Loader.CallTemplateFunction(TemplateHelper.ClearTemplateCacheFunctionName);

            // Run the pre generation template function.

            var data = new PreGenerationData
            {
                OutputFolder = SharedData.CurrentProject.ProjectSettings.OutputPath,
                OverwriteFiles = SharedData.CurrentProject.ProjectSettings.OverwriteFiles
            };

            foreach (var uo in SharedData.CurrentProject.Options.Where(o => o.IsVirtualProperty == false))
            {
                var optionValue = SharedData.CurrentProject.GetUserOption(uo.VariableName);
                data.UserOptions.Add(uo.VariableName, optionValue);
            }
            foreach (var provider in SharedData.CurrentProject.Providers)
            {
                ArchAngel.Interfaces.ProviderInfo[] otherProviders = new ProviderInfo[SharedData.CurrentProject.Providers.Count];
                SharedData.CurrentProject.Providers.CopyTo(otherProviders);
                data.OtherProviderInfos = otherProviders.ToList();
                data.OtherProviderInfos.Remove(provider);
                _Loader.CallPreGenerationInitialisationFunction(provider, data);
            }
            ((ProjectFileTree)parentNode).TreeRestructuring = true;
            ((ProjectFileTree)parentNode).Clear();
            ArchAngel.Interfaces.SharedData.CurrentProject.ScriptProject.OutputFolder = project.OutputFolder;
            ArchAngel.Interfaces.SharedData.CurrentProject.ScriptProject.TempFolder = project.TempFolder;
            ArchAngel.Interfaces.SharedData.CurrentProject.InitialiseScriptObjects();
            SetProjectInCode(ArchAngel.Interfaces.SharedData.CurrentProject.ScriptProject);
            project = ArchAngel.Interfaces.SharedData.CurrentProject.ScriptProject;
            //SetProjectInCode(project);

            ////////////////////////////////////////

            // TODO: Check for duplicate files and folders
            ScriptProject = project;
            NumFiles = 0;
            //SkipFileProperty = CurrentAssembly.GetType("Slyce.FunctionRunner.FunctionProcessor").GetProperty("SkipCurrentFile");

            foreach (Folder subFolder in templateProject.OutputFolder.Folders)
                ProcessFolder(subFolder, targetFolder, parentNode);

            foreach (ArchAngel.Interfaces.Template.File file in templateProject.OutputFolder.Files)
                ProcessFile(file, targetFolder, parentNode, null);

            foreach (ArchAngel.Interfaces.Template.StaticFile staticFile in templateProject.OutputFolder.StaticFiles)
                ProcessStaticFile(staticFile, targetFolder, parentNode);

            targetFolder += Path.DirectorySeparatorChar.ToString();
            duplicateFiles = new List<FilenameInfo>();

            foreach (var f in AllTextFilenames)
                f.RelativePath = f.RelativePath.Replace(targetFolder, "");

            foreach (var group in AllTextFilenames.GroupBy(n => n.RelativePath).Where(g => g.Count() > 1))
                duplicateFiles.AddRange(group.Select(g => g));

            return NumFiles;
        }
Esempio n. 9
0
        /// <summary>
        /// Populates the provider with the saved data from the given project file.
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="projectFilePath"></param>
        public static void PopulateProviderFromProjectFile(ProviderInfo provider, string projectFilePath)
        {
            if (string.IsNullOrEmpty(projectFilePath)) throw new ArgumentException("Project File path cannot be empty");
            if (provider == null) throw new ArgumentException("Provider to populate cannot be null");

            DirectoryInfo parent = Directory.GetParent(projectFilePath);
            if (parent != null)
            {
                string projectDirectory = parent.FullName;
                string folder = GetProjectFilesFolder(projectFilePath);
                string providerDirectory = Path.Combine(projectDirectory, folder);

                PopulateProvider(provider, providerDirectory);
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Returns the path string of the folder where assemblies are temporarily put for processing.
 /// The directory is not created.
 /// </summary>
 /// <param name="provider">The provider to get the assembly name from.</param>
 /// <returns>A temporary path to place files associated with a provider.</returns>
 public static string GetProviderTempFolder(ProviderInfo provider)
 {
     return Path.GetTempPath().PathSlash("ArchAngel").PathSlash("ProviderTemp")
         .PathSlash(provider.Assembly.GetName().Name.Replace(".", "_") + "Temp");
 }
Esempio n. 11
0
        internal IScriptBaseObject[] GetIteratorObjects(Type iteratorType, ProviderInfo provider)
        {
            if (CurrentRootObject == null)
            {
                return provider.GetAllObjectsOfType(iteratorType.FullName).ToArray();
            }
            if (iteratorType.IsInstanceOfType(CurrentRootObject))
            {
                return new[] { CurrentRootObject };
            }

            return provider.GetAllObjectsOfType(iteratorType.FullName, CurrentRootObject).ToArray();
        }
Esempio n. 12
0
        public void InitialiseScriptObjects()
        {
            var data = new PreGenerationData
            {
                OutputFolder = this.ProjectSettings.OutputPath,
                OverwriteFiles = this.ProjectSettings.OverwriteFiles
            };

            foreach (var uo in this.Options.Where(o => o.IsVirtualProperty == false))
            {
                var optionValue = this.GetUserOption(uo.VariableName);
                data.UserOptions.Add(uo.VariableName, optionValue);
            }
            foreach (var provider in this.Providers)
            {
                ArchAngel.Interfaces.ProviderInfo[] otherProviders = new ProviderInfo[this.Providers.Count];
                this.Providers.CopyTo(otherProviders);
                data.OtherProviderInfos = otherProviders.ToList();
                data.OtherProviderInfos.Remove(provider);
                //provider.InitialiseScriptObjects(data);
            }
            foreach (var provider in this.Providers)
                provider.InitialiseScriptObjects(data);
        }
Esempio n. 13
0
        public Type GetIteratorTypeFromProviders(string typeName, out ProviderInfo provider)
        {
            foreach (ProviderInfo providerObject in Providers)
            {
                Type iteratorType = providerObject.Assembly.GetType(typeName);
                if (iteratorType == null) continue; // Not found in this assembly

                provider = providerObject;
                return iteratorType;
            }

            // We couldn't find the assembly. Try figure out why.
            // Search the currently loaded assemblies.
            var allAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
            foreach (var assem in allAssemblies)
            {
                if (assem.GetType(typeName) != null)
                {
                    // Type exists in another assembly.
                    throw new TypeNotAnIteratorException(typeName,
                        string.Format("Type {0} does not exist in Provider assemblies, but was found in {1}",
                        typeName, assem.FullName));
                }
            }

            throw new TypeDoesNotExistException(typeName,
                string.Format("The IteratorType {0} could not be found in any assembly. This is an issue with the Template, please contact the template author.", typeName));
        }