示例#1
0
        /// <summary>
        /// Création d'une nouvelle classe
        /// </summary>
        /// <param name="elem">The elem.</param>
        /// <param name="layer">The layer.</param>
        /// <returns></returns>
        private static ClassImplementation CreateClass(CandleElement elem, Layer layer)
        {
            string name = StrategyManager.GetInstance(elem.Store).NamingStrategy.CreateElementName(layer, elem.RootName);

            // On regarde d'abord si il n'existe pas une classe du même nom
            foreach (ClassImplementation cl in layer.Classes)
            {
                if (cl.Name == name)
                {
                    return(cl);
                }
            }

            // Sinon création d'une nouvelle
            ClassImplementation clazz = new ClassImplementation(layer.Store);

            clazz.RootName = elem.RootName;
            clazz.Name     = name;
            clazz.Comment  = elem.Comment;
            layer.Classes.Add(clazz);

            UnplacedModelHelper.RegisterNewModel(layer.Store, clazz);
            return(clazz);
        }
示例#2
0
        /// <summary>
        /// Création d'un scenario
        /// </summary>
        /// <param name="elem">The elem.</param>
        /// <param name="layer">The layer.</param>
        /// <returns></returns>
        private static Scenario CreateScenario(CandleElement elem, UIWorkflowLayer layer)
        {
            string name = StrategyManager.GetInstance(elem.Store).NamingStrategy.CreateElementName(layer, elem.RootName);

            // On regarde d'abord si il n'existe pas une classe du même nom
            foreach (Scenario cl in layer.Scenarios)
            {
                if (cl.Name == name)
                {
                    return(cl);
                }
            }

            // Sinon création d'une nouvelle
            Scenario scenario = new Scenario(layer.Store);

            scenario.RootName = elem.RootName;
            scenario.Name     = name;
            scenario.Comment  = elem.Comment;
            layer.Scenarios.Add(scenario);

            UnplacedModelHelper.RegisterNewModel(layer.Store, scenario);
            return(scenario);
        }
示例#3
0
        /// <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();
                    }
                }
            }
        }
示例#4
0
 /// <summary>
 /// Nom du répertoire (logique) contenant le projet
 /// </summary>
 /// <returns></returns>
 public virtual string GetProjectFolderName()
 {
     return(StrategyManager.GetInstance(this.Store).NamingStrategy.CreateProjectFolderName(this, null));
 }
        /// <summary>
        /// Alerts listeners that a property for an element has changed.
        /// </summary>
        /// <param name="e">Provides data for the ElementPropertyChanged event.</param>
        public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
        {
            // Teste si on est en train de charger le modèle
            // Permet d'eviter de déclencher une régle lors du chargement du modèle
            if (e.ModelElement.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.IsSerializing ||
                e.ModelElement.Store.InUndoRedoOrRollback)
            {
                return;
            }
            object value;

            // On ignore
            if (
                e.ModelElement.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.
                TryGetValue("CustomizableElementChangeRule_Enabled", out value) &&
                (bool)value == false)
            {
                return;
            }

            CandleElement elem = e.ModelElement as CandleElement;

            if (elem == null)
            {
                return;
            }

            // Teste l'élément
            //if (e.DomainProperty.Id == ClassImplementation.NameDomainPropertyId)
            //{
            //    if (String.IsNullOrEmpty(elem.RootName) || elem.RootName == (string)e.OldValue)
            //        elem.RootName = elem.Name;
            //}

            if (e.DomainProperty.Id == CandleElement.RootNameDomainPropertyId)
            {
                string oldValue           = (string)e.OldValue;
                ClassImplementation model = e.ModelElement as ClassImplementation;
                if (model != null)
                {
                    // NON si on force le root name, c'est qu'on veut changer le nom
                    //string oldName = String.IsNullOrEmpty(oldValue) ? null : StrategyManager.GetInstance(model.Store).NamingStrategy.CreateElementName(model.Layer, oldValue);
                    //if( String.IsNullOrEmpty(elem.Name) || elem.Name == oldName || String.IsNullOrEmpty(oldValue))
                    elem.Name =
                        StrategyManager.GetInstance(model.Store).NamingStrategy.CreateElementName(model.Layer,
                                                                                                  (string)e.NewValue);

                    if (model.Contract != null)
                    {
                        model.Contract.RootName = model.RootName;
                    }
                }

                ServiceContract contract = e.ModelElement as ServiceContract;
                if (contract != null && contract.Layer != null && contract.Name == "?")
                // Layer est null si on a à faire à un ExternalServiceContract
                {
                    //string oldName = StrategyManager.GetInstance(clazz.Store).NamingStrategy.CreateElementName(contract.Layer, (string)e.OldValue);
                    //if (String.IsNullOrEmpty(elem.Name) || elem.Name == oldName)
                    elem.Name =
                        StrategyManager.GetInstance(contract.Store).NamingStrategy.CreateElementName(contract.Layer,
                                                                                                     (string)e.NewValue);
                }

                Entity entity = e.ModelElement as Entity;
                if (entity != null)
                {
                    DataLayer modelsLayer = entity.Package.Layer;
                    string    oldName     = String.IsNullOrEmpty(oldValue)
                                         ? null
                                         : StrategyManager.GetInstance(model.Store).NamingStrategy.CreateElementName(
                        model.Layer, oldValue);
                    if (String.IsNullOrEmpty(elem.Name) || elem.Name == oldName || String.IsNullOrEmpty(oldValue))
                    {
                        elem.Name =
                            StrategyManager.GetInstance(elem.Store).NamingStrategy.CreateElementName(modelsLayer,
                                                                                                     (string)e.NewValue);
                    }
                }
            }
        }
示例#6
0
        /// <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();
                }
            }
        }
示例#7
0
 /// <summary>
 /// Handles the KeyUp event of the txtRootName control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
 private void txtRootName_KeyUp(object sender, KeyEventArgs e)
 {
     txtEntityName.Text =
         StrategyManager.GetInstance(_layer.Store).NamingStrategy.CreateElementName(_layer, txtRootName.Text);
 }
示例#8
0
        /// <summary>
        /// Coinstructeur
        /// </summary>
        /// <param name="component">The component.</param>
        public ApplicationNamespaceForm(SoftwareComponent component)
        {
            Debug.Assert(component != null);

            _component = component;
            InitializeComponent();

            string txt = component.Namespace;

            if (String.IsNullOrEmpty(txt) && component.Model != null)
            {
                txt = component.Model.Name;
            }

            if (txt == "?")
            {
                txt = string.Empty;
                try
                {
                    if (component.Model != null)
                    {
                        txt = StrategyManager.GetInstance(component.Store).NamingStrategy.DefaultNamespace;
                    }
                }
                catch
                {
                    txt = String.Empty;
                }

                try
                {
                    if (txt != null && txt.Length > 0)
                    {
                        txt += '.';
                    }
                    txt += (string)ServiceLocator.Instance.ShellHelper.Solution.Properties.Item(9).Value;
                }
                catch
                {
                    txt = String.Empty;
                }
            }
            txtNamespace.Text = txt;

            UpdateApplicationName();

            if (component.Model != null)
            {
                ckLibrary.Checked = component.Model.IsLibrary;
                VersionInfo version = component.Model.Version;
                if (version != null)
                {
                    txtVersionBuild.Value    = version.Build > 0 ? version.Build : 0;
                    txtVersionMajor.Value    = version.Major > 0 ? version.Major : 0;
                    txtVersionMinor.Value    = version.Minor > 0 ? version.Minor : 0;
                    txtVersionRevision.Value = version.Revision > 0 ? version.Revision : 0;
                }
            }
            txtDomainPath.Text  = component.Model.Path;
            txtDescription.Text = component.Comment;
        }
示例#9
0
 /// <summary>
 /// Calling paremeters list (paramName1, paramName2...)
 /// </summary>
 /// <returns></returns>
 public string CreateParameterList()
 {
     return(StrategyManager.GetInstance(Store).TargetLanguage.CreateParameterList(this));
 }
示例#10
0
        /// <summary>
        /// Quand la cellule pert le focus, on ajoute une ligne
        /// en dessous suivant le contexte si c'est possible
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.DataGridViewCellEventArgs"></see> that contains the event data.</param>
        /// <exception cref="T:System.ArgumentOutOfRangeException">The value of the <see cref="P:System.Windows.Forms.DataGridViewCellEventArgs.ColumnIndex"></see> property of e is greater than the number of columns in the control minus one.-or-The value of the <see cref="P:System.Windows.Forms.DataGridViewCellEventArgs.RowIndex"></see> property of e is greater than the number of rows in the control minus one.</exception>
        protected override void OnCellValidated(DataGridViewCellEventArgs e)
        {
            base.OnCellValidated(e);

            try
            {
                // 1 ére ligne (Entete)
                if (e.RowIndex == 0 || _root == null || _root.Store == null)
                {
                    return;
                }

                // Si on est sur une catégorie, on ne fait toujours rien
                VirtualTreeGridItem value = GetRowValue(e.RowIndex);
                // Si le nom saisie n'est pas valable ou si on est en readonly, on ne valide pas
                if (value == null || value.ReadOnly || String.IsNullOrEmpty(value.Name) ||
                    !StrategyManager.GetInstance(_root.Store).NamingStrategy.IsClassNameValid(value.Name))
                {
                    return;
                }

                bool isNewValue = value.IsNewValue; // Est on sur une ligne nouvelle ?

                // Vérification si l'utilisateur peut sortir de la cellule
                VirtualTreeGridDataChangedEventsArgs arg = new VirtualTreeGridDataChangedEventsArgs(value);
                OnDataChanged(arg);
                if (arg.Cancel)
                {
                    return;
                }

                // Si on était sur la 1ère colonne, création d'une ligne supplémentaire
                if (e.ColumnIndex == 0)
                {
                    if (isNewValue)
                    {
                        if (value.Kind == ModelKind.Member)
                        {
                            //VirtualTreeGridItem methodValue = value as VirtualTreeGridItem;

                            if (value.DataItem is IHasChildren)
                            {
                                value.Collapse = false;
                                _members.Add(
                                    new VirtualTreeGridItem(value.Category, (IHasChildren)value.DataItem,
                                                            ModelKind.Child));
                            }

                            _members.Add(new VirtualTreeGridItem(value.Category, value.Parent, ModelKind.Member));

                            if (value.DataItem is IHasChildren)
                            {
                                ExpandCollapseRow(Rows.Count - 2, false);
                            }
                        }
                        else if (value.Kind == ModelKind.Child)
                        {
                            //VirtualTreeGridItem argValue = value as VirtualTreeGridItem;
                            _members.Insert(e.RowIndex + 1,
                                            new VirtualTreeGridItem(value.Category, value.Parent, ModelKind.Child));
                        }
                    }
                }
            }
            finally
            {
                _inPlaceEditMode = false;
            }
        }
示例#11
0
 /// <summary>
 /// Updates the name of the assembly.
 /// </summary>
 /// <param name="layer">The layer.</param>
 private static void UpdateAssemblyName(SoftwareLayer layer)
 {
     layer.AssemblyName = StrategyManager.GetInstance(layer.Store).NamingStrategy.CreateAssemblyName(layer);
 }
示例#12
0
文件: Layer.cs 项目: malain/candle
 /// <summary>
 /// Nom du répertoire (logique) contenant le projet
 /// </summary>
 /// <returns></returns>
 public override string GetProjectFolderName()
 {
     return(StrategyManager.GetInstance(Store).NamingStrategy.CreateProjectFolderName(this, LayerPackage.Name));
 }
示例#13
0
        /// <summary>
        /// Imports the operations.
        /// </summary>
        /// <param name="layer">The layer.</param>
        /// <param name="port">The port.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>true if the import is ok</returns>
        public bool ImportOperations(SoftwareLayer layer, TypeWithOperations port, string fileName)
        {
            FileCodeModel fcm = ServiceLocator.Instance.ShellHelper.GetFileCodeModel(fileName);

            if (fcm == null)
            {
                return(false);
            }

            foreach (CodeElement cn in fcm.CodeElements)
            {
                if (cn is CodeNamespace)
                {
                    foreach (CodeElement ci in ((CodeNamespace)cn).Members)
                    {
                        if ((ci is CodeInterface || ci is CodeClass) && layer is InterfaceLayer)
                        {
                            CodeElements members;
                            string       comment;
                            if (ci is CodeInterface)
                            {
                                comment = ((CodeInterface)ci).DocComment;
                                members = ((CodeInterface)ci).Members;
                            }
                            else
                            {
                                comment = ((CodeClass)ci).DocComment;
                                members = ((CodeClass)ci).Members;
                            }
                            if (port == null)
                            {
                                port          = new ServiceContract(layer.Store);
                                port.Name     = ci.Name;
                                port.RootName = ci.Name;
                                port.Comment  = NormalizeComment(comment);
                                ((InterfaceLayer)layer).ServiceContracts.Add((ServiceContract)port);
                            }

                            RetrieveOperations(port, members, false);
                        }
                        else if (ci is CodeClass && layer is Layer)
                        {
                            CodeClass           cc    = ci as CodeClass;
                            ClassImplementation clazz = port as ClassImplementation;
                            //if (cc.Access == vsCMAccess.vsCMAccessPublic)
                            {
                                if (clazz == null)
                                {
                                    clazz          = new ClassImplementation(layer.Store);
                                    clazz.Name     = ci.Name;
                                    clazz.RootName = ci.Name;
                                    clazz.Comment  = NormalizeComment(cc.DocComment);
                                    ((Layer)layer).Classes.Add(clazz);
                                }

                                InterfaceLayer iLayer = clazz.Layer.LayerPackage.InterfaceLayer;
                                // Si il y a plusieurs interfaces, on ne fait rien car on ne sait pas laquelle prendre
                                if (iLayer != null && cc.ImplementedInterfaces.Count == 1)
                                {
                                    ServiceContract contract = clazz.Contract;
                                    if (contract == null)
                                    {
                                        string iName = cc.ImplementedInterfaces.Item(1).Name;
                                        contract = iLayer.ServiceContracts.Find(delegate(ServiceContract c) { return(c.Name == iName); });
                                        if (contract == null)
                                        {
                                            contract          = new ServiceContract(layer.Store);
                                            contract.Name     = StrategyManager.GetInstance(clazz.Store).NamingStrategy.CreateElementName(iLayer, cc.Name);
                                            contract.RootName = cc.Name;
                                            contract.Comment  = NormalizeComment(cc.DocComment);
                                            iLayer.ServiceContracts.Add(contract);
                                            RetrieveOperations(contract, cc.Members, true);
                                        }
                                        clazz.Contract = contract;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(true);
        }
示例#14
0
        /// <summary>
        /// Execution du wizard
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DSLFactory.Candle.SystemModel.Strategies.StrategyElementElementAddedEventArgs"/> instance containing the event data.</param>
        public void RunWizard(ModelElement sender, StrategyElementElementAddedEventArgs e)
        {
            CandleElement elem = e.ModelElement as CandleElement;

            txtRootName.Text = elem.RootName;

            if (elem is ServiceContract) // Ce cas est désactivé (voir selection du wizard)
            {
                _layer       = ((ServiceContract)e.ModelElement).Layer;
                txtName.Text =
                    StrategyManager.GetInstance(_layer.Store).NamingStrategy.CreateElementName(_layer, elem.RootName);
            }
            else
            {
                _layer       = ((ClassImplementation)e.ModelElement).Layer;
                _iLayer      = ((ClassImplementation)e.ModelElement).Layer.LayerPackage.InterfaceLayer;
                txtName.Text =
                    StrategyManager.GetInstance(_layer.Store).NamingStrategy.CreateElementName(_layer, elem.RootName);
                if (_iLayer == null)
                {
                    txtContractName.Visible = false;
                }
                else
                {
                    txtContractName.Text =
                        StrategyManager.GetInstance(_layer.Store).NamingStrategy.CreateElementName(_iLayer, txtName.Text);
                }
            }

            if (elem is ServiceContract || ((ClassImplementation)elem).Layer.LayerPackage.InterfaceLayer == null)
            {
                lblContractName.Visible = false;
                txtContractName.Visible = false;
                txtContractName.Text    = null;
            }

            lblHeader.Text = String.Format(lblHeader.Text, _layer.Name);
            groupBox1.Text = _layer.Namespace;

            if (!s_dontShow)
            {
                e.UserCancel = (ShowDialog() == DialogResult.Cancel);
                if (e.UserCancel)
                {
                    return;
                }
                s_dontShow = ckDontShow.Checked;
            }

            // Ici on force les noms des classes donc on ne veut pas que la régle basée sur la modification
            // du RootName s'execute. On l'indique dans le contexte de la transaction
            if (
                !elem.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.ContainsKey(
                    "CustomizableElementChangeRule_Enabled"))
            {
                elem.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.Add(
                    "CustomizableElementChangeRule_Enabled", false);
            }
            elem.Name = txtName.Text;

            using (Transaction transaction = elem.Store.TransactionManager.BeginTransaction("Set root name"))
            {
                // Force la transaction pour que la règle s'execute tout de suite et qu'on puisse
                // forcer le nom ensuite
                elem.RootName = txtRootName.Text;
                transaction.Commit();
            }

            // Si c'est une classe, on essaye de créer son interface
            ClassImplementation clazz = elem as ClassImplementation;

            if (clazz != null && _iLayer != null && !String.IsNullOrEmpty(txtContractName.Text))
            {
                if (clazz.Contract == null)
                {
                    // On regarde si l'interface n'existe pas
                    clazz.Contract =
                        _iLayer.ServiceContracts.Find(
                            delegate(ServiceContract c) { return(c.Name == txtContractName.Text); });

                    if (clazz.Contract == null)
                    {
                        clazz.Contract          = new ServiceContract(clazz.Store);
                        clazz.Contract.RootName = txtRootName.Text;
                        clazz.Layer.LayerPackage.InterfaceLayer.ServiceContracts.Add(clazz.Contract);
                        UnplacedModelHelper.RegisterNewModel(clazz.Store, clazz.Contract);

                        // Si la classe courante utilise un seul contract, on le recopie
                        IList <ClassUsesOperations> links = ClassUsesOperations.GetLinksToServicesUsed(clazz);
                        if (links.Count == 1)
                        {
                            ServiceContract contract = links[0].TargetService as ServiceContract;
                            if (contract != null)
                            {
                                TypeWithOperations.CopyOperations(contract, clazz.Contract);
                            }
                            else
                            {
                                ExternalServiceContract externalContract =
                                    links[0].TargetService as ExternalServiceContract;
                                if (externalContract != null)
                                {
                                    TypeWithOperations.CopyOperations(externalContract.ReferencedServiceContract,
                                                                      clazz.Contract);
                                }
                            }
                        }
                    }
                }

                using (Transaction transaction = elem.Store.TransactionManager.BeginTransaction("Set root name"))
                {
                    // Force la transaction pour que la règle s'execute tout de suite et qu'on puisse
                    // forcer le nom ensuite
                    clazz.Contract.RootName = elem.RootName;
                    transaction.Commit();
                }

                if (clazz.Contract.Name != txtContractName.Text)
                {
                    clazz.Contract.Name = txtContractName.Text;
                }
            }

            e.CancelBubble = true;
        }