Exemplo n.º 1
0
        /// <summary>
        /// Recherche du template de génération
        /// </summary>
        /// <param name="layer">The layer.</param>
        /// <returns></returns>
        public string GetProjectTemplate(SoftwareLayer layer)
        {
            // Le template de la couche est prioritaire
            if (!string.IsNullOrEmpty(layer.Template))
            {
                return(layer.Template);
            }

            // Puis on cherche dans les autres stratégies
            foreach (StrategyBase strategy in layer.GetStrategies(true))
            {
                if (strategy is IStrategyProvidesProjectTemplates && strategy != this)
                {
                    string projectTemplate = ((IStrategyProvidesProjectTemplates)strategy).GetProjectTemplate(layer);
                    if (!String.IsNullOrEmpty(projectTemplate))
                    {
                        return(projectTemplate);
                    }
                }
            }

            // Puis celui de la stratégie courante
            if (!String.IsNullOrEmpty(ProjectTemplate))
            {
                return(ProjectTemplate);
            }

            // Valeur par défaut
            if (layer is Layer && ((Layer)layer).HostingContext == HostingContext.Web)
            {
                return(StrategyManager.GetInstance(layer.Store).TargetLanguage.DefaultWebLibraryTemplateName);
            }

            return(StrategyManager.GetInstance(layer.Store).TargetLanguage.DefaultLibraryTemplateName);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Récupére la liste des stratégies applicables et actives sur un modéle
        /// </summary>
        /// <param name="strategiesOwner">The strategies owner.</param>
        /// <param name="element">Elément concerné ou null pour tous</param>
        /// <returns></returns>
        internal static List <StrategyBase> GetStrategies(CandleElement strategiesOwner, ICustomizableElement element)
        {
            ILogger logger = ServiceLocator.Instance.GetService <ILogger>();

            List <StrategyBase> strategies = new List <StrategyBase>();

            if (strategiesOwner == null)
            {
                return(strategies);
            }

            if (element != null && logger != null)
            {
                logger.BeginStep(String.Concat("Get enabled strategies for element ", element.Name, " (id=", element.Id, ")"), LogType.Debug);
            }

            foreach (StrategyBase strategy in StrategyManager.GetInstance(strategiesOwner.Store).GetStrategies(strategiesOwner, true))
            {
                if (strategy.IsEnabled)
                {
                    strategies.Add(strategy);
                }
                else
                if (element != null && logger != null)
                {
                    logger.Write("GetStrategies", String.Concat("Strategy ", strategy.StrategyId, " ignored because it is disabled"), LogType.Debug);
                }
            }
            if (element != null && logger != null)
            {
                logger.EndStep();
            }

            return(strategies);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RunningStrategiesForm"/> class.
        /// </summary>
        /// <param name="element">The element.</param>
        public RunningStrategiesForm(CandleElement element)
        {
            InitializeComponent();

            btnOK.Enabled = false;

            chkPass.Items.Clear();
            chkPass.Items.Add(GenerationPass.MetaModelUpdate, true);
            chkPass.Items.Add(GenerationPass.CodeGeneration, true);
            chkPass.Items.Add(GenerationPass.ElementAdded, false);

            lstStrategies.Items.Clear();
            if (element != null)
            {
                foreach (
                    StrategyBase strategy in StrategyManager.GetInstance(element.Store).GetStrategies(element, true))
                {
                    ListViewItem item = new ListViewItem(strategy.DisplayName);
                    item.SubItems.Add(strategy.Description);
                    item.Checked = true;
                    item.Tag     = strategy;
                    lstStrategies.Items.Add(item);
                    btnOK.Enabled = true;
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Handles the Click event of the btnGo control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUrl.Text.Length == 0)
                {
                    _manifests = StrategyManager.GetAvailableManifests();
                }
                else
                {
                    ManifestCollection tmp = new ManifestCollection();
                    tmp.AddRange(RepositoryManager.GetExternalManifests(txtUrl.Text));
                    foreach (StrategyManifest mf in tmp)
                    {
                        mf.PackageName = String.Format("{0}@{1}", mf.PackageName, txtUrl.Text);
                    }
                    _manifests = tmp;
                }

                if (rbTree.Checked)
                {
                    PopulateTreeView();
                }
                else
                {
                    PopulateListView();
                }
            }
            catch (Exception ex)
            {
                ServiceLocator.Instance.IDEHelper.ShowError(
                    String.Format("Unable to retrieve strategies from {0} - {1}", txtUrl.Text, ex.Message));
            }
        }
        /// <summary>
        /// Gets the properties.
        /// </summary>
        /// <param name="attributes">The attributes.</param>
        /// <returns></returns>
        public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            PropertyDescriptorCollection properties = base.GetProperties(attributes);

            // Recherche dans les stratégies associés à ce modèle
            if (ModelElement is ICustomizableElement && !ModelElement.IsDeleted)
            {
                foreach (
                    StrategyBase strategy in
                    StrategyManager.GetStrategies(((ICustomizableElement)ModelElement).StrategiesOwner, null))
                // On prend toutes les stratégies
                {
                    try
                    {
                        foreach (PropertyDescriptor prop in strategy.GetCustomProperties(ModelElement))
                        {
                            properties.Add(prop);
                        }
                    }
                    catch
                    {
                    }
                }
            }
            return(properties);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Affichage du source correspondant à un élément. Si plusieurs fichiers
        /// correspondent, une fenètre de sélection est affichée
        /// </summary>
        /// <param name="elementId">ID de l'élément</param>
        /// <param name="className">Nom de la classe ou null</param>
        /// <param name="operationName">Nom de la méthode ou null</param>
        public void ShowCode(Guid elementId, string className, string operationName)
        {
            try
            {
                // Recherche des fichiers générés
                List <string> files1 = GetFiles(elementId, false);
                List <string> files2 = GetFiles(elementId, true);

                string fileName = null;
                if (files1.Count == 0 && files2.Count == 0)
                {
                    // On essaye de chercher le fichier dans la solution
                    fileName =
                        String.Concat(className, StrategyManager.GetInstance(_model.Store).TargetLanguage.Extension);
                    ProjectItem item = ServiceLocator.Instance.ShellHelper.FindProjectItemByFileName(null, fileName);
                    if (item == null)
                    {
                        return; // Aucun
                    }
                    fileName = item.get_FileNames(1);
                }
                else if (files1.Count == 1 && files2.Count == 0)
                {
                    fileName = files1[0];
                }
                else if (files1.Count == 0 && files2.Count == 1)
                {
                    fileName = files2[0];
                }
                else
                {
                    // Il y en a plusieurs, on affiche une fenètre de sélection
                    SelectFile dlg = new SelectFile(files1, files2);
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        fileName = dlg.SelectedFile;
                    }
                }

                if (fileName != null)
                {
                    ServiceLocator.Instance.ShellHelper.TryToShow(fileName, className, operationName);
                }
            }
            catch (Exception ex)
            {
                ILogger logger = ServiceLocator.Instance.GetService <ILogger>();
                if (logger != null)
                {
                    logger.WriteError("Show code", "Unable to show code for " + className, ex);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Chargement des stratégies disponibles sous forme d'arbre organisé
        /// par StrategyPath
        /// </summary>
        /// <param name="strategiesOwner">The strategies owner.</param>
        /// <param name="selectedStrategy">The selected strategy.</param>
        private void PopulateListView(CandleElement strategiesOwner, StrategyBase selectedStrategy)
        {
            this._strategiesOwner = strategiesOwner != null ? strategiesOwner.StrategiesOwner : null;

            Dictionary <string, ListViewGroup> groups = new Dictionary <string, ListViewGroup>();

            // Evite l'evenement OnItemChecked
            _initialize = true;
            lvStrategies.Items.Clear();

            //
            // Lecture de toutes les strategies disponibles
            //
            foreach (StrategyBase strategy in StrategyManager.GetInstance(_store).GetStrategies(strategiesOwner, false))
            {
                // Création du noeud de la stratégie
                ListViewItem item = new ListViewItem(strategy.DisplayName);
                //
                // Recherche si les strategies possédent des attributs de description
                //
                string strategyGroup = "Standard";
                foreach (
                    StrategyAttribute customAttribute in
                    strategy.GetType().GetCustomAttributes(typeof(StrategyAttribute), false))
                {
                    if (!String.IsNullOrEmpty(customAttribute.Description))
                    {
                        strategy.Description = customAttribute.Description;
                    }
                    if (!String.IsNullOrEmpty(customAttribute.StrategyGroup))
                    {
                        strategyGroup          = customAttribute.StrategyGroup;
                        strategy.StrategyGroup = strategyGroup;
                    }
                }
                item.Group   = FindGroup(groups, strategyGroup);
                item.Tag     = strategy;
                item.Checked = strategy.IsEnabled;
                lvStrategies.Items.Add(item);
                item.Selected = selectedStrategy != null && selectedStrategy == strategy;
            }

            _initialize = false;

            ListViewGroup[] temp = new ListViewGroup[groups.Values.Count];
            groups.Values.CopyTo(temp, 0);
            //Array.Sort(temp);
            lvStrategies.Groups.AddRange(temp);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Suppression d'une stratégie
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnRemove_Click(object sender, EventArgs e)
        {
            StrategyBase strategy = SelectedStrategy;

            if (strategy != null && ServiceLocator.Instance.IDEHelper.Confirm())
            {
                StrategyManager.GetInstance(_store).RemoveStrategy(_strategiesOwner, strategy);

                propGrid.SelectedObject = null;
                Populate(_strategiesOwner, null);

                OnStrategyRemoved(
                    new StrategyRemovedEventArgs(strategy, StrategyManager.GetStrategyOwnerName(_strategiesOwner)));
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Ajout d'une stratégie
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            SelectStrategyDialog dlg = new SelectStrategyDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                foreach (StrategyManifest manifest in dlg.SelectedStrategies)
                {
                    // On ne rajoute la stratégie que si elle n'y est pas dèjà
                    StrategyBase strategy = StrategyManager.GetInstance(_store).AddStrategy(_strategiesOwner, manifest);
                    if (strategy != null)
                    {
                        Populate(_strategiesOwner, strategy);
                    }
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Bouton OK. Vérification qu'il n'y ait pas de doublons dans les ID et que ceux ci soient valides.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            foreach (StrategiesListControl ctrl in specificStrategies)
            {
                if (!ctrl.CommitChanges())
                {
                    return;
                }
            }

            if (globalsStrategies.CommitChanges())
            {
                // TODO verif doublons entre les deux tabpages.
                RemoveStrategiesCode();
                StrategyManager.GetInstance(_store).Save(_store);
                DialogResult = DialogResult.OK;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Création du fichier dans le projet
        /// </summary>
        /// <param name="prj">Projet contenant le fichier</param>
        /// <param name="element">Elément concerné ou null</param>
        /// <param name="fileName">Nom du fichier ou null (default: element.Name)</param>
        /// <returns>Chemin complet du fichier</returns>
        protected string CreateOutputFileName(Project prj, ICustomizableElement element, string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                fileName = element.Name;
            }

            if (!Path.HasExtension(fileName))
            {
                fileName =
                    String.Format("{0}{1}", fileName,
                                  StrategyManager.GetInstance(_currentElement.Store).TargetLanguage.Extension);
            }

            // On le prend tel quel
            string tmpFileName = fileName;

            if (tmpFileName.Length > 0 && tmpFileName[0] == '~')
            {
                tmpFileName = tmpFileName.Substring(1);
            }
            else
            {
                // Si il n'y a que le nom du fichier, on prend le pattern par défaut
                if (Path.GetFileName(tmpFileName) == tmpFileName)
                {
                    string pattern = DefaultGeneratedFilePathPattern;
                    if (String.IsNullOrEmpty(pattern))
                    {
                        pattern =
                            StrategyManager.GetInstance(_currentElement.Store).NamingStrategy.
                            DefaultGeneratedCodeFilePattern;
                    }
                    tmpFileName = String.Format(pattern, tmpFileName);
                }
            }

            tmpFileName = ResolvePattern(element, tmpFileName);

            // Suppression du '/' de debut
            if (tmpFileName.Length > 1 &&
                (tmpFileName[0] == Path.AltDirectorySeparatorChar || tmpFileName[0] == Path.DirectorySeparatorChar))
            {
                tmpFileName = tmpFileName.Substring(1);
            }

            string pathName = tmpFileName.Replace('/', '\\');

            if (pathName.Length > 0 && pathName[0] == '\\')
            {
                pathName = pathName.Substring(1);
            }
            // Permet de surcharger
            pathName = CreateRelativeOutputFileName(element, pathName);

            Debug.Assert(pathName.Length > 0 && pathName[0] != '\\', "the file name must be relatif");
            Debug.Assert(Path.HasExtension(pathName), "file name must have an extension");
            Debug.Assert(pathName.IndexOf('{') < 0, "incorrect file name");
            Context.RelativeGeneratedFileName = pathName;
            return(Context.ProjectFolder != null?Path.Combine(Context.ProjectFolder, pathName) : pathName);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Génération du mapping des propriétés
        /// </summary>
        /// <param name="level"></param>
        /// <param name="root"></param>
        /// <param name="componentName"></param>
        private void GenerateMappingProperties(int level, Entity clazz, string componentName)
        {
            this.WriteLineWithIndent(level, "<!--  Properties    -->");

            foreach (DSLFactory.Candle.SystemModel.Property prop in clazz.Properties)
            {
                if (prop.IsPrimaryKey || prop.IsForeignKey)
                {
                    continue;
                }

                string   typeName = prop.Type;
                DataType refType  = _inheritanceTree.FindEntityByName(prop.Type);
                if (refType != null)
                {
                    typeName = refType.AssemblyQualifiedName;
                }
                else
                {
                    // C'est peut-être une énumération
                    refType = clazz.DataLayer.FindType(prop.Type) as Enumeration;
                    if (refType != null)
                    {
                        typeName = refType.FullName;
                    }
                }

                string columnName = prop.ColumnName;
                if (string.IsNullOrEmpty(columnName))
                {
                    columnName = StrategyManager.GetInstance(clazz.Store).NamingStrategy.CreateSQLColumnName(componentName, prop.Name);
                }

                // Propriété simple
                IList <string> types = ClrTypeParser.GetModelNamesFromClrType(prop.Type);
                if (types == null || types.Count == 0 || refType is Enumeration)
                {
                    this.WriteLineWithIndent(level, String.Format("<property name=\"{0}\" column=\"{1}\" type=\"{2}\"/>", prop.Name, columnName, typeName));
                }
                else
                {
                    // Component
                    this.WriteLineWithIndent(level, String.Format("<component name=\"{0}\" class=\"{1}\" >", prop.Name, typeName));

                    Entity entity = refType as Entity;
                    if (entity != null)
                    {
                        GenerateMappingProperties(level + 1, entity, columnName);

                        // Propriétés des classes de bases
                        while (entity.SuperClass != null)
                        {
                            entity = entity.SuperClass;
                            GenerateMappingProperties(level + 1, entity, columnName);
                        }
                    }
                    this.WriteLineWithIndent(level, "</component>");
                }
            }


            IList <Association> list = Association.GetLinksToTargets(clazz);

            foreach (Association association in list)
            {
                if (association.SourceMultiplicity == Multiplicity.OneMany || association.SourceMultiplicity == Multiplicity.ZeroMany)
                {
                    string lazy = NHibernateStrategy.AssociationLazyLoadingProperty.GetValue(association).ToString().ToLower();

                    this.WriteLine("");
                    this.WriteLineWithIndent(level, "<!-- Relation  0..* -->");
                    this.WriteLineWithIndent(level, "<bag ");
                    this.WriteLineWithIndent(level, String.Format("    name=\"{0}\" inverse=\"true\" lazy=\"{1}\" >", association.SourceRoleName, lazy));
                    this.WriteLineWithIndent(level, String.Format("    <key column=\"{0}\"/>", association.SourceRoleName));
                    this.WriteLineWithIndent(level, String.Format("    <one-to-many class=\"{0}\" />", association.Target.AssemblyQualifiedName));
                    this.WriteLineWithIndent(level, "</bag>");
                }
                else if (association.SourceMultiplicity != Multiplicity.NotApplicable)
                {
                    string insert    = NHibernateStrategy.AssociationInsertProperty.GetValue(association).ToString().ToLower();
                    string update    = NHibernateStrategy.AssociationUpdateProperty.GetValue(association).ToString().ToLower();
                    string outerJoin = NHibernateStrategy.AssociationOuterJoinProperty.GetValue(association).ToString().ToLower();
                    this.WriteLineWithIndent(level, String.Format("<many-to-one name=\"{0}\" class=\"{1}\" insert=\"{2}\" update=\"{3}\"  outer-join=\"{4}\">", association.SourceRoleName, association.Target.AssemblyQualifiedName, insert, update, outerJoin));
                    foreach (ForeignKey fk in association.ForeignKeys)
                    {
                        WriteColumn(level + 1, "<column name=\"{0}\"/>", fk.Column);
                    }
                    this.WriteLineWithIndent(level, "</many-to-one>");
                }
            }

            list = Association.GetLinksToSources(clazz);
            foreach (Association association in list)
            {
                if (association.TargetMultiplicity != Multiplicity.NotApplicable && !String.IsNullOrEmpty(association.TargetRoleName))
                {
                    string lazy = NHibernateStrategy.AssociationLazyLoadingProperty.GetValue(association).ToString().ToLower();

                    this.WriteLine("");
                    this.WriteLineWithIndent(level, "<!-- Relation  0..* -->");
                    this.WriteLineWithIndent(level, "<bag ");
                    this.WriteLineWithIndent(level, String.Format("    name=\"{0}\" inverse=\"true\" lazy=\"{1}\" >", association.TargetRoleName, lazy));
                    if (association.ForeignKeys.Count == 1)
                    {
                        WriteColumn(level + 1, "<key column=\"{0}\"/>", association.ForeignKeys[0].Column);
                    }
                    else
                    {
                        this.WriteLineWithIndent(level + 1, "<key>");
                        foreach (ForeignKey fk in association.ForeignKeys)
                        {
                            WriteColumn(level + 2, "<column name=\"{0}\"/>", fk.Column);
                        }
                        this.WriteLineWithIndent(level + 1, "</key>");
                    }
                    this.WriteLineWithIndent(level + 1, String.Format("<one-to-many class=\"{0}\" />", association.Source.AssemblyQualifiedName));
                    this.WriteLineWithIndent(level, "</bag>");
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Génération du mapping d'une classe
        /// </summary>
        /// <param name="root">Classe sur lequel s'effectue le mapping</param>
        /// <param name="level">Niveau d'indentation dans le fichier de sortie</param>
        private void GenerateClassMapping(ClassInheritanceNode root, int level, int discriminator)
        {
            if (root.IsExternal)
            {
                return;
            }

            // Si cette classe n'est pas persistable, on ne fait rien y compris sur ses sous classes
            bool isPersistable = NHibernateStrategy.EntityIsPersistableProperty.GetValue(root.clazz);

            if (isPersistable == false)
            {
                return;
            }

            string endTag = "</class>";

            if (level == 1)
            {
                bool   isRootClass = root.childs.Count > 0;
                string tableName   = root.clazz.TableName;
                if (String.IsNullOrEmpty(tableName))
                {
                    tableName = root.clazz.Name;
                }
                string schema = root.clazz.TableOwner;
                if (!String.IsNullOrEmpty(schema))
                {
                    schema = String.Format("schema=\"{0}\"", schema);
                }

                this.WriteLine("");
                string comment = String.Format("<!--                        Mapping de la classe {0}                  -->", root.clazz.Name);
                string asterix = new string('*', comment.Length - 9);
                this.WriteLineWithIndent(0, String.Format("<!-- {0} -->", asterix));
                this.WriteLineWithIndent(0, comment);
                this.WriteLineWithIndent(0, String.Format("<!-- {0} -->", asterix));
                this.WriteLineWithIndent(0, String.Format("<class name=\"{0}\" table=\"{1}\" {2}>", root.clazz.AssemblyQualifiedName, tableName, (isRootClass ? " discriminator-value=\"0\"" : "")));

                // Identifiant
                if (root.clazz.PrimaryKeys.Count == 0)
                {
                    this.WriteLineWithIndent(1, "<id><generator/></id>");
                }
                else if (root.clazz.PrimaryKeys.Count == 1)
                {
                    Property prop       = root.clazz.PrimaryKeys[0];
                    string   columnName = prop.ColumnName;
                    if (string.IsNullOrEmpty(columnName))
                    {
                        columnName = StrategyManager.GetInstance(root.clazz.Store).NamingStrategy.CreateSQLColumnName(root.clazz.Name, prop.Name);
                    }
                    this.WriteLineWithIndent(1, String.Format("<id name=\"{0}\" column=\"{1}\">", prop.Name, columnName));

                    GeneratorInfo gi = NHibernateStrategy.EntityIdGeneratorProperty.GetValue(root.clazz);
                    if (gi != null)
                    {
                        this.WriteLineWithIndent(2, String.Format("<generator class=\"{0}\">", gi.Name));
                        foreach (GeneratorInfo.GeneratorParm parm in gi.Parms)
                        {
                            this.WriteLineWithIndent(3, String.Format("<param name=\"{0}\">{1}</param>", parm.Name, parm.Value));
                        }
                        this.WriteLineWithIndent(2, "</generator>");
                    }
                    this.WriteLineWithIndent(1, "</id>");
                }
                else // Count > 1
                {
                    this.WriteLineWithIndent(1, String.Format("<composite-id name=\"Key\" class=\"{0}+PrimaryKey,{1}\">", root.clazz.FullName, root.clazz.DataLayer.AssemblyName));
                    foreach (Property property in root.clazz.PrimaryKeys)
                    {
                        string columnName = property.ColumnName;
                        if (string.IsNullOrEmpty(columnName))
                        {
                            columnName = StrategyManager.GetInstance(root.clazz.Store).NamingStrategy.CreateSQLColumnName(root.clazz.Name, property.Name);
                        }

                        this.WriteLineWithIndent(2, String.Format("<key-property name=\"{0}\" column=\"{1}\"/>", property.Name, columnName));
                    }
                    this.WriteLineWithIndent(1, "</composite-id>");
                }

                if (isRootClass)
                {
                    this.WriteLineWithIndent(1, "<!-- Mapping utilise la stratégie de mapping filtré -->");
                    this.WriteLineWithIndent(1, "<discriminator column=\"DiscriminatorValue\" type=\"Int16\" force=\"true\"/>");
                }
            }
            else
            {
                endTag = "</subclass>";
                this.WriteLine("");
                string comment = String.Format("<!--                       sub-class mapping : {0}                  -->", root.clazz.Name);
                string asterix = new string('*', comment.Length - 9);
                this.WriteLineWithIndent(0, String.Format("<!-- {0} -->", asterix));
                this.WriteLineWithIndent(0, comment);
                this.WriteLineWithIndent(0, String.Format("<!-- {0} -->", asterix));
                this.WriteLineWithIndent(level, String.Format("<subclass name=\"{0}\" discriminator-value=\"{1}\" >", root.clazz.AssemblyQualifiedName, (1 << (discriminator - 1))));
            }

            // Génération des propriétés de la classe
            GenerateMappingProperties(level, root.clazz, null);

            // Génération des sous classes
            foreach (ClassInheritanceNode childNode in root.childs)
            {
                GenerateClassMapping(childNode, level + 1, discriminator);
                discriminator++;
            }

            // Fermeture du tag
            this.WriteLineWithIndent(level - 1, endTag);
        }
Exemplo n.º 14
0
        /// <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);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Initialisation de la liste des stratégies à partir de celles disponibles sur le
 /// repository central + les stratégies internes
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void SelectStrategyDialog_Load(object sender, EventArgs e)
 {
     _manifests = StrategyManager.GetAvailableManifests();
     PopulateListView();
 }
Exemplo n.º 16
0
        /// <summary>
        /// Récupère les stratégies du modèle courant.
        /// </summary>
        /// <param name="store"></param>
        /// <remarks>
        /// Si un autre modèle est ouvert dans la solution, on retourne un manager ne contenant aucune strategie.
        /// </remarks>
        /// <returns></returns>
        public static IStrategyManager GetInstance(Store store)
        {
            // Modèle correspondant au store
            CandleModel model = CandleModel.GetInstance(store);

            if (model == null) // On a pas trouvé le modèle, on retourne un strategyManager vide
            {
                return(new StrategyManager());
            }

            // Si on a dèja chargé les stratégies, on les retourne
            if (s_currentModelId != Guid.Empty && s_currentModelId == model.Id)
            {
                return(s_currentStrategyManager);
            }

            // Est ce que c'est le modèle courant
            CandleModel currentModel = CandleModel.GetModelFromCurrentSolution();

            if (currentModel == null || currentModel.Id != model.Id)
            {
                return(new StrategyManager());
            }

            // Sinon on va créer les stratégies
            SuspendWatcher(false);

            // Flag indiquant si on peut persister les stratégies ou seulement les initialiser.
            // On ne peut pas persister si on est dans le cas d'une initialisation du modèle puisqu'on ne connait pas
            // encore le nom du modèle
            bool   canPersist       = true;
            string strategyFileName = null;

            try
            {
                // Création d'un nouveau fichier de strategies ayant le même nom que le modèle mais avec
                // l'extension .strategies
                string modelFileName = model.FileName;

                // Dans le cas d'une création d'un modèle, on ne peut pas récupérer le filepath du modèle car
                // il n'y a pas encore de vue active. Dans ce cas, on essaye de le déduire.
                if (modelFileName == null)
                {
                    string name = model.Name;

                    // On est dans le cas d'une initialisation de modèle, on ne va crèer le fichier des stratégies tout de suite
                    // on attend que le modèle soit initialisé
                    if (name.Contains("?"))
                    {
                        canPersist       = false;
                        strategyFileName = Path.GetTempFileName();  // Fichier temporaire pour récupèrer les stratégies pré-initialisées
                        Utils.DeleteFile(strategyFileName);         // Obligé car GetTempFileName crée le fichier
                    }
                    else
                    {
                        IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();
                        if (shell != null)
                        {
                            string tmp = Path.GetFileNameWithoutExtension(shell.GetSolutionAssociatedModelName());
                            if (!String.IsNullOrEmpty(tmp))
                            {
                                name = tmp;
                            }
                            else
                            {
                                tmp = shell.Solution.FullName;
                                if (!String.IsNullOrEmpty(tmp))
                                {
                                    name = Path.GetFileNameWithoutExtension(tmp);
                                }
                            }
                        }

                        strategyFileName = String.Concat(Path.Combine(ServiceLocator.Instance.ShellHelper.SolutionFolder, name), DefaultStrategiesFileNameExtension);
                    }
                }
                else
                {
                    strategyFileName = Path.ChangeExtension(modelFileName, DefaultStrategiesFileNameExtension);
                }

                // Initialisation du fichier de stratégies à partir d'un modèle
                if (!String.IsNullOrEmpty(model.StrategyTemplate))
                {
                    EnsureStrategiesFileExists(strategyFileName, model.StrategyTemplate, canPersist);
                }

                StrategyManager manager = null;
                if (File.Exists(strategyFileName))
                {
                    manager = Load(store, strategyFileName);
                }
                else
                {
                    manager = new StrategyManager();
                }

                if (canPersist)
                {
                    manager.FileName = strategyFileName;
                    // Cache pour éviter de le relire
                    s_currentModelId         = model.Id;
                    s_currentStrategyManager = manager;
                }

                return(manager);
            }
            finally
            {
                SuspendWatcher(true);

                // Suppression du fichier temporaire
                if (!canPersist)
                {
                    Utils.DeleteFile(strategyFileName);
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StrategiesForm"/> class.
        /// </summary>
        /// <param name="component">The component.</param>
        /// <param name="model">The model.</param>
        public StrategiesForm(SoftwareComponent component, CandleElement model)
        {
            InitializeComponent();

            if (component != null)
            {
                _store = component.Store;
            }
            else
            {
                _store = model.Store;
            }

            specificStrategies = new List <StrategiesListControl>();
            globalsStrategies  = new StrategiesListControl();
            namingStrategy     = new NamingStrategyControl();
            languageConfig     = new LanguageConfigurationControl();

            globalsStrategies.Dock     = DockStyle.Fill;
            globalsStrategies.Name     = "globalsStrategies";
            globalsStrategies.TabIndex = 1;

            namingStrategy.Dock     = DockStyle.Fill;
            namingStrategy.Name     = "namingStrategy";
            namingStrategy.TabIndex = 1;

            languageConfig.Dock     = DockStyle.Fill;
            languageConfig.Name     = "languageConfig";
            languageConfig.TabIndex = 1;

            tabStrategies.TabPages.Clear();

            // Création des onglets (une par couche + une globale + une pour la stratégie de nommage)
            // L'onglet courant est sélectionné

            // D'abord le global
            globalsStrategies.Initialize(_store, null);
            tabGlobals.Controls.Add(globalsStrategies);
            tabStrategies.TabPages.Add(tabGlobals);

            // Puis un par couche
            int index = 1;

            foreach (SoftwareLayer layer in component.Layers)
            {
                StrategiesListControl specificStrategy = new StrategiesListControl();
                specificStrategy.Dock     = DockStyle.Fill;
                specificStrategy.Name     = String.Format("specificStrategies{0}", index);
                specificStrategy.TabIndex = 0;
                specificStrategy.Initialize(_store, layer);
                specificStrategy.StrategyRemoved += Strategies_StrategyRemoved;

                TabPage tabSpecific = new TabPage();
                tabStrategies.TabPages.Add(tabSpecific);

                tabSpecific.Location = new Point(4, 22);
                tabSpecific.Name     = String.Format("tabSpecific{0}", index);
                tabSpecific.Padding  = new Padding(3);
                tabSpecific.Size     = new Size(741, 348);
                tabSpecific.TabIndex = index;
                tabSpecific.UseVisualStyleBackColor = true;

                tabSpecific.Text = layer.Name;
                if (layer == model.StrategiesOwner)
                {
                    tabSpecific.Text         += "*";
                    tabStrategies.SelectedTab = tabSpecific;
                }
                tabSpecific.Controls.Add(specificStrategy);
            }


            // Stratégie de nommage
            namingStrategy.Initialize(StrategyManager.GetInstance(_store).NamingStrategy);
            tabNaming.Controls.Add(namingStrategy);
            tabStrategies.TabPages.Add(tabNaming);

            // Et le language
            languageConfig.Initialize(StrategyManager.GetInstance(_store).TargetLanguage);
            tabLanguage.Controls.Add(languageConfig);
            tabStrategies.TabPages.Add(tabLanguage);

            globalsStrategies.StrategyRemoved += new EventHandler <StrategyRemovedEventArgs>(Strategies_StrategyRemoved);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initialisation de la liste des stratégies
        /// </summary>
        /// <param name="strategiesOwner">The strategies owner.</param>
        /// <param name="selectedStrategy">The selected strategy.</param>
        private void PopulateTreeView(CandleElement strategiesOwner, StrategyBase selectedStrategy)
        {
            this._strategiesOwner = strategiesOwner != null ? strategiesOwner.StrategiesOwner : null;
            _initialize           = true;
            tvStrategies.Nodes.Clear();

            // Remplissage à partir des stratégies liées au modèle
            TreeNode selectedNode = null;

            foreach (StrategyBase strategy in StrategyManager.GetInstance(_store).GetStrategies(strategiesOwner, false))
            {
                TreeNodeCollection nodes = tvStrategies.Nodes;

                // Insertion dans l'arbre en tenant compte du path
                if (!String.IsNullOrEmpty(strategy.StrategyPath))
                {
                    string[] pathParts = strategy.StrategyPath.Split('/');
                    // Création ou recherche de l'arborescence liée au path
                    foreach (string part in pathParts)
                    {
                        // Recherche du noeud parent pour chaque part
                        bool bFind = false;
                        foreach (TreeNode node in nodes)
                        {
                            if (Utils.StringCompareEquals(node.Text, part))
                            {
                                nodes = node.Nodes;
                                bFind = true;
                                break;
                            }
                        }

                        // Si pas trouvé, on le crèe
                        if (!bFind)
                        {
                            TreeNode parent = new TreeNode(part);
                            nodes.Add(parent);
                            nodes = parent.Nodes;
                            parent.Expand();
                        }
                    }
                }

                // Création du noeud de la stratégie
                TreeNode tmpNode = new TreeNode(strategy.DisplayName);
                tmpNode.Tag = strategy;
                nodes.Add(tmpNode);
                tmpNode.Checked = strategy.IsEnabled;
                if (selectedStrategy != null && selectedStrategy.StrategyId == strategy.StrategyId)
                {
                    selectedNode = tmpNode;
                }
            }

            if (selectedNode != null)
            {
                tvStrategies.SelectedNode = selectedNode;
            }

            _initialize = false;
        }