/// <summary> /// Création d'un type si il n'existe pas. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public string CreateTypeIfNotExists(string type) { DataType t = null; // le test suivant ne peut pas être null car son appel va générer la création // de la couche modèles si elle n'existe pas. C'est bien ce que l'on veut if (DataLayer != null) { // On va demander confirmation pour créer le type. t = FindGlobalType(type); if (t == null) { // Si le type ne contient pas de ., on va chercher ce type dans tous // les namespaces. if (type.IndexOf('.') <= 0) { List <DataType> types = FindAllTypesFromSingleName(type); // Si il n'y a qu'un, on le prend if (types.Count == 1) { return(types[0].FullName); } // Si il y en a plusieurs, il faut le sélectionner if (types.Count != 0) { TypeSelectorDialog dlg = new TypeSelectorDialog(types); switch (dlg.ShowDialog()) { // Il veut en créer case DialogResult.Cancel: t = EnsureTypeExists(type); break; // On ne fait plus rien, il garde le nom initial case DialogResult.Ignore: return(type); // Il en a sélectionné un case DialogResult.OK: return(dlg.SelectedType); } } } IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>(); if (ide != null) { if (ide.ShowMessageBox(String.Format("Do you want to create the type '{0}' in the models layer ?", type), "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes) { t = EnsureTypeExists(type); } } } } return(t == null ? type : t.FullName); }
/// <summary> /// Création de l'instance de la strategie contenu dans le manifest /// </summary> /// <param name="owner"></param> /// <param name="manifest">Manifest contenant la stratégie</param> /// <returns></returns> public StrategyBase AddStrategy(CandleElement owner, StrategyManifest manifest) { InternalPackage package = GetPackage(manifest.PackageName); if (package == null) { return(null); } StrategyBase strategy = package.CreateStrategyInstance(manifest.StrategyTypeName, manifest.StrategyConfiguration); if (strategy != null) { strategy.Owner = GetStrategyOwnerName(owner); // Vérification des doublons foreach (StrategyBase other in _strategies) { if (other.Owner == strategy.Owner && other.StrategyId == strategy.StrategyId) { return(other); } } try { strategy.OnLoading(this, new EventArgs()); _strategies.Add(strategy); } catch (Exception ex) { IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>(); if (ide != null) { ide.ShowMessageBox("Error when loading strategy " + strategy.DisplayName + " : " + ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK); ide.LogError(false, "Error when loading strategy " + strategy.DisplayName + " : " + ex.Message, 0, 0, "StrategyManager"); } } } return(strategy); }
/// <summary> /// Import des tables /// </summary> /// <param name="connection">The connection.</param> /// <param name="parentPackage">The parent package.</param> /// <param name="dbObjects">The db objects.</param> /// <param name="dbType">Type of the db.</param> public void Import(IDbConnection connection, Package parentPackage, List <DbContainer> dbObjects, DatabaseType dbType) { ILogger logger = ServiceLocator.Instance.GetService <ILogger>(); _layer = parentPackage.Layer; ISchemaDiscover schemaDiscover = GetSchemaDiscover(connection); string connectionTypeName = connection != null?connection.GetType().Name : "??unknow??"; if (schemaDiscover == null) { if (logger != null) { logger.Write("Import DbTable", "schema discover not found for connection " + connectionTypeName, LogType.Error); } return; } string providerName = connection.GetType().Namespace; try { parentPackage.Layer.AddXmlConfigurationContent("ConnectionStrings", String.Format( @"<configuration><connectionStrings><add name=""{0}"" connectionString=""{1}"" providerName=""{2}""/></connectionStrings></configuration>", connectionTypeName, connection.ConnectionString.Replace('"', ' '), providerName)); } catch (Exception cfgEx) { if (logger != null) { logger.WriteError("Import DbTable", "Registering connectionString", cfgEx); } } // Création des entités foreach (DbContainer dbContainer in dbObjects) { try { // On recherche si il n'y a pas dèjà une classe qui pointe sur la même table Entity doublon = FindEntity(dbContainer.Name); if (doublon != null) { IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>(); if (ide != null) { if ( ide.ShowMessageBox( String.Concat("The entity ", doublon.Name, " is binding to the same table. Do you want to continue ?"), "Warning", MessageBoxButtons.YesNo) == DialogResult.No) { continue; } } } dbContainer.Connection = connection; using ( Transaction transaction = parentPackage.Store.TransactionManager.BeginTransaction("Add entity from DB")) { transaction.Context.ContextInfo.Add( dbType == DatabaseType.Table ? ImportedTableInfo : ImportedProcedureInfo, dbContainer); Entity entity = new Entity(parentPackage.Store); EntityNameConfirmation dlg = new EntityNameConfirmation(parentPackage.Layer, dbContainer.Name); if (dlg.ShowDialog() == DialogResult.Cancel) { continue; } entity.DatabaseType = dbType; entity.RootName = dlg.RootName; entity.Name = dlg.EntityName; entity.TableName = dbContainer.Name; entity.TableOwner = dbContainer.Owner; entity.DatabaseType = dbType; parentPackage.Types.Add(entity); dbContainer.Entity = entity; List <DbColumn> columns = null; DbTable dbTable = dbContainer as DbTable; if (dbTable != null) { List <DbIndex> indexes = schemaDiscover.GetIndexes(dbTable); dbTable.Indexes = indexes; columns = schemaDiscover.GetColumns(dbTable); } else if (dbContainer is DbStoredProcedure) { columns = schemaDiscover.GetColumns(dbContainer as DbStoredProcedure); } dbContainer.Columns = columns; foreach (DbColumn column in columns) { using ( Transaction transaction2 = parentPackage.Store.TransactionManager.BeginTransaction("Add column in entity")) { transaction2.Context.ContextInfo.Add(ImportedColumnInfo, column); Property property = new Property(entity.Store); property.Name = StrategyManager.GetInstance(property.Store).NamingStrategy.ToPascalCasing( column.Name); property.RootName = property.Name; property.ColumnName = column.Name; property.Type = column.ClrType.FullName; property.Nullable = column.IsNullable; property.ServerType = column.ServerType; property.IsPrimaryKey = column.InPrimaryKey; property.IsAutoIncrement = column.IsAutoIncrement; entity.Properties.Add(property); column.Property = property; transaction2.Commit(); } } transaction.Commit(); } } catch (Exception ex) { if (logger != null) { logger.WriteError("Import table", String.Format("Error when importing table {0}", dbContainer.Name), ex); } } } if (dbType == DatabaseType.StoredProcedure) { return; } // Puis on crée les liens foreach (DbTable table in dbObjects) { List <DbRelationShip> relations = schemaDiscover.GetRelations(table); foreach (DbRelationShip relation in relations) { Entity sourceEntity = FindEntity(relation.SourceTableName); Entity targetEntity = FindEntity(relation.TargetTableName); if (targetEntity == null || sourceEntity == null) { continue; } if (Association.GetLinks(sourceEntity, targetEntity).Count > 0) { continue; } using ( Transaction transaction = parentPackage.Store.TransactionManager.BeginTransaction("Create relations")) { transaction.Context.ContextInfo.Add(ImportedRelationInfo, relation); Association association = new Association(sourceEntity, targetEntity); association.Sort = AssociationSort.Normal; // Calcul du nom // Si il n'existe pas d'autres relations avec le même modèle, on // prend le nom du modèle cible if (CountSameRelations(relations, relation) == 1) { association.SourceRoleName = targetEntity.Name; } else { association.SourceRoleName = relation.Name; } //On ajoute les propriétés concernées dans la liste des propriétes //liées à l'association for (int idx = 0; idx < relation.SourceColumnNames.Count; idx++) { string sourceColumnName = relation.SourceColumnNames[idx]; ForeignKey fk = new ForeignKey(sourceEntity.Store); fk.Column = sourceEntity.Properties.Find( delegate(Property prop) { return(prop.ColumnName == sourceColumnName); }); string targetColumnName = relation.TargetColumnNames[idx]; fk.PrimaryKey = targetEntity.Properties.Find( delegate(Property prop) { return(prop.ColumnName == targetColumnName); }); if (fk.PrimaryKey != null && fk.Column != null) { association.ForeignKeys.Add(fk); } } transaction.Commit(); } } } }
/// <summary> /// Chargement /// </summary> /// <param name="store">The store.</param> /// <param name="fileName">Name of the file.</param> /// <returns></returns> public static StrategyManager Load(Store store, string fileName) { ILogger logger = ServiceLocator.Instance.GetService <ILogger>(); if (String.IsNullOrEmpty(fileName)) { return(null); } StrategyManager sm = null; try { using (StreamReader reader = new StreamReader(fileName)) { // Désérialization de la description XmlSerializer serializer = new XmlSerializer(typeof(StrategyManager)); sm = (StrategyManager)serializer.Deserialize(reader); // Lecture et chargement des types List <Type> types = new List <Type>(); foreach (StrategyTypeReference str in sm.StrategyTypes) { InternalPackage package = sm.GetPackage(str.PackageName); if (package != null) { Type type = package.GetStrategyType(str.StrategyTypeName); if (type != null) { types.Add(type); } } } // D'abord chargement de la stratégie de nommage if (sm.NamingStrategyNode != null) { using (XmlNodeReader nr = new XmlNodeReader(sm.NamingStrategyNode)) { serializer = new XmlSerializer(typeof(BaseNamingStrategy), types.ToArray()); sm._namingStrategy = (INamingStrategy)serializer.Deserialize(nr); } } // Chargement des strategies if (sm.StrategiesNode != null) { using (XmlNodeReader nr = new XmlNodeReader(sm.StrategiesNode)) { serializer = new XmlSerializer(typeof(StrategyCollection), types.ToArray()); sm._strategies = (StrategyCollection)serializer.Deserialize(nr); } foreach (StrategyBase strategy in sm._strategies) { try { strategy.OnLoading(sm, new EventArgs()); StrategyPackage package = sm.GetPackage(strategy.PackageName) as StrategyPackage; if (package != null) { strategy.StrategyFolder = package.PackageFolder; } } catch (Exception ex) { IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>(); if (ide != null) { ide.ShowMessageBox("Error when loading strategy " + strategy.DisplayName + " : " + ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK); ide.LogError(false, "Error when loading strategy " + strategy.DisplayName + " : " + ex.Message, 0, 0, "StrategyManager"); } } } } } } catch (Exception ex) { string text = ex.Message; XmlException xex = ex as XmlException; StringBuilder sb = new StringBuilder(ex.Message); if (xex != null) { sb.AppendFormat(" line={0}, column={1}", xex.LineNumber, xex.LinePosition); } Exception iex = ex.InnerException; while (iex != null) { sb.Append(" - "); sb.Append(iex.Message); iex = iex.InnerException; } text = sb.ToString(); if (logger != null) { logger.WriteError("StrategyManager", String.Format("Loading error {0}", text), ex); } IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>(); if (ide != null) { ide.ShowMessage("Error when reading the strategies file (see error in the task list). A new empty file will be initialized. The current strategies file will be saved with a .bak extension"); } try { // Sauvegarde du fichier en erreur if (File.Exists(fileName)) { Utils.CopyFile(fileName, fileName + ".bak"); } } catch { } } if (sm == null) { // Génération d'un fichier par défaut sm = new StrategyManager(); sm.FileName = fileName; sm.Save(store); } else { sm.FileName = fileName; } return(sm); }
/// <summary> /// Generates the specified service provider. /// </summary> /// <param name="serviceProvider">The service provider.</param> /// <param name="modelFileName">Name of the model file.</param> /// <param name="selectedElement">The selected element.</param> public static void Generate(IServiceProvider serviceProvider, string modelFileName, ICustomizableElement selectedElement) { if (modelFileName == null) { throw new ArgumentNullException("modelFileName"); } ILogger logger = ServiceLocator.Instance.GetService <ILogger>(); IIDEHelper ide = ServiceLocator.Instance.IDEHelper; Generator.s_serviceProvider = serviceProvider; try { // Sauvegarde de tous les documents ServiceLocator.Instance.ShellHelper.Solution.DTE.Documents.SaveAll(); CandleModel model = CandleModel.GetModelFromCurrentSolution(modelFileName); // Chargement du modèle //ModelLoader loader = ModelLoader.GetLoader(modelFileName, false); //if (loader == null || loader.Model == null) //{ // if (logger != null) // logger.Write("Generator", "unable to load the model", LogType.Error); // return; //} //CandleModel model = loader.Model; if (model.Component == null) { if (logger != null) { logger.Write("Generator", "model contains no software component.", LogType.Error); } return; } if (StrategyManager.GetInstance(model.Store).GetStrategies(null, true).Count == 0) { if (logger != null) { logger.Write("Generator", "No strategies configured.", LogType.Error); } return; } // CandleModel model = loader.Model; s_context = new GenerationContext(model, modelFileName, selectedElement != null ? selectedElement.Id : Guid.Empty); GenerationPass generationPassesSelected = GenerationPass.CodeGeneration | GenerationPass.MetaModelUpdate; try { // Demande des stratégies à executer if (selectedElement != null) { RunningStrategiesForm dlg = new RunningStrategiesForm(selectedElement.StrategiesOwner); if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { return; } s_context.SelectedStrategies = dlg.SelectedStrategies; generationPassesSelected = dlg.SelectedGenerationPasses; } if (logger != null) { logger.BeginProcess(true, true); } // Préparation de l'IDE ide.SetWaitCursor(); ide.DisplayProgress("Generate...", 1, 3); Microsoft.VisualStudio.Modeling.Validation.ValidationContext vc = new Microsoft.VisualStudio.Modeling.Validation.ValidationContext(Microsoft.VisualStudio.Modeling.Validation.ValidationCategories.Save, model); if (vc.CurrentViolations.Count > 0) { if (ide != null) { if (ide.ShowMessageBox("There is validation errors, continue generate ?", "Generation", MessageBoxButtons.YesNo) == DialogResult.No) { return; } } } // Au cas ou cette passe a été forcé dans la boite de dialogue if ((generationPassesSelected & GenerationPass.ElementAdded) == GenerationPass.ElementAdded) { if (logger != null) { logger.BeginStep("Code Generation for the ElementAdded event", LogType.Info); } s_context.GenerationPass = GenerationPass.ElementAdded; using (Transaction transaction = model.Store.TransactionManager.BeginTransaction("Update metamodel")) { model.Component.GenerateCode(s_context); transaction.Commit(); } if (logger != null) { logger.EndStep(); } } // Mise à jour du méta modèle if ((generationPassesSelected & GenerationPass.MetaModelUpdate) == GenerationPass.MetaModelUpdate) { if (logger != null) { logger.BeginStep("1) Meta Model Update", LogType.Info); } s_context.GenerationPass = GenerationPass.MetaModelUpdate; using (Transaction transaction = model.Store.TransactionManager.BeginTransaction("Update metamodel")) { // On ne veut pas que les wizards soient appelés model.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo[StrategyManager.IgnoreStrategyWizards] = true; model.Component.GenerateCode(s_context); if (transaction.HasPendingChanges) { transaction.Commit(); } } if (logger != null) { logger.EndStep(); } } if (logger != null) { logger.BeginStep("1) Check references", LogType.Info); } // Vérification des dépendances ReferencesHelper.CheckReferences(true, vc, new ConfigurationMode(), ReferenceScope.Compilation, model); if (logger != null) { logger.EndStep(); } ide.DisplayProgress("Generate...", 2, 3); // Génération de code if ((generationPassesSelected & GenerationPass.CodeGeneration) == GenerationPass.CodeGeneration) { if (logger != null) { logger.BeginStep("2) Code Generation", LogType.Info); } s_context.GenerationPass = GenerationPass.CodeGeneration; model.Component.GenerateCode(s_context); if (logger != null) { logger.EndStep(); } } } finally { Mapper.Instance.Save(); } //if (logger != null) // logger.BeginStep("Generation epilogue", LogType.Debug); //if (logger != null) // logger.EndStep(); } catch (Exception ex) { if (logger != null) { logger.WriteError("Generator", "Generator", ex); } } finally { // On s'assure de faire disparaitre la progress bar ide.DisplayProgress("", 2, 0); if (logger != null) { logger.EndProcess(); } if (ide != null) { ide.ShowErrorList(); } } }