Example #1
0
        // Lors de la création d'un element, on va afficher un wizard que l'utilisateur peut annuler.
        // TIPS permet d'intercepter la création d'un enfant
        /// <summary>
        /// Execution d'un wizard lors de la création d'un élément
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="defaultWizard">The default wizard.</param>
        /// <returns></returns>
        public bool ExecuteWizard(ModelElement element, IStrategyWizard defaultWizard)
        {
            if (!(element is ICustomizableElement))
            {
                return(true);
            }

            try
            {
                StrategyElementElementAddedEventArgs e = new StrategyElementElementAddedEventArgs(element);

                foreach (StrategyBase strategy in GetStrategies(false))
                {
                    IStrategyAddElementInterceptor sa = strategy as IStrategyAddElementInterceptor;
                    if (sa == null)
                    {
                        continue;
                    }
                    IStrategyWizard wizard = sa.GetWizard(element);
                    if (wizard != null)
                    {
                        wizard.RunWizard(this, e);
                        if (e.UserCancel)
                        {
                            return(false);
                        }

                        if (e.CancelBubble)
                        {
                            break;
                        }
                    }
                }

                if (!e.CancelBubble && defaultWizard != null)
                {
                    defaultWizard.RunWizard(this, e);
                    if (e.UserCancel)
                    {
                        return(false);
                    }
                }

                OnElementAdded(e);

                Generator.GenerateWhenElementAdded(this.Store, CandleModel.GetInstance(this.Store), element as ICustomizableElement);
                return(true);
            }
            catch (Exception ex)
            {
                IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>();
                if (ide != null)
                {
                    ide.ShowMessage(ex.Message);
                }
                return(false);
            }
        }
Example #2
0
        /// <summary>
        /// Extraction des fichiers du package et chargement des assemblies
        /// </summary>
        public void Extract()
        {
            Utils.RemoveDirectory(PackageFolder);
            if (Directory.Exists(PackageFolder) && Directory.GetFiles(PackageFolder, ".dll").Length > 0)
            {
                IIDEHelper ide = ServiceLocator.Instance.IDEHelper;
                if (ide != null)
                {
                    ide.ShowMessage(
                        String.Format("Change detected in strategies package {0} - You must restart Visual Studio",
                                      _name));
                }
            }

            Directory.CreateDirectory(PackageFolder);

            RepositoryZipFile zip = new RepositoryZipFile(FullName, true);

            zip.ExtractAll(PackageFolder);
        }
Example #3
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);
        }
Example #4
0
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider sp, object value)
        {
            ModelElement model = context.Instance as ModelElement;

            if (model == null)
            {
                return(value);
            }

            _edSvc = (IWindowsFormsEditorService)sp.GetService(typeof(IWindowsFormsEditorService));
            if (_edSvc != null)
            {
                _comboBox = new ComboBox();
                _comboBox.DropDownStyle = ComboBoxStyle.Simple;

                int num1 = 0;
                SoftwareComponent component = CandleModel.GetInstance(model.Store).SoftwareComponent;
                string            item1     = PopulateListBoxItems(component.GetDefinedTypeNames(), out num1);
                _comboBox.Size         = new Size(num1 + 10, 120);
                _comboBox.KeyDown     += KeyDown;
                _comboBox.Leave       += ValueChanged;
                _comboBox.DoubleClick += ValueChanged;
                _comboBox.Click       += ValueChanged;
                _edSvc.DropDownControl(_comboBox);
                if (_comboBox.Text.Length == 0)
                {
                    return(value);
                }
                string item2 = _comboBox.Text;
                if ((item2 == null) || (item1 == item2))
                {
                    return(value);
                }

                if (!String.IsNullOrEmpty(item2))
                {
                    bool shouldCreateModel = false;
                    ClrTypeParser.Parse(item2, delegate(string typeName)
                    {
                        shouldCreateModel = true;
                        return(typeName);
                    });

                    // Si il y a des types à créer, il faut que la couche modèle existe
                    if (shouldCreateModel && component.DataLayer == null)
                    {
                        IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>();
                        if (ide != null)
                        {
                            ide.ShowMessage(
                                String.Format("Can't create user type '{0}' because the models layer does not exist.",
                                              item2));
                        }
                    }
                    else
                    {
                        return(item2);
                    }
                }
            }
            return(value);
        }
Example #5
0
        /// <summary>
        /// Vérification si un type existe et le crée le cas échéant (y compris les packages)
        /// </summary>
        /// <param name="newTypeName">Nom complet du type</param>
        /// <returns>Une instance du type</returns>
        public DataType EnsureTypeExists(string newTypeName)
        {
            if (String.IsNullOrEmpty(newTypeName))
            {
                return(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)
            {
                IIDEHelper ide = ServiceLocator.Instance.GetService <IIDEHelper>();
                if (ide != null)
                {
                    ide.ShowMessage(String.Format("Can't create user type '{0}' because the models layer does not exist.", newTypeName));
                }
                throw new DataLayerNotDefinedException();
            }

            if (!IsDataLayerExists)
            {
                return(null);
            }

            if (this.Store.TransactionManager.CurrentTransaction.Context.ContextInfo.ContainsKey("ReverseInProgress"))
            {
                return(null);
            }

            DataType  newDefinedTypeModel = null;
            DataLayer modelsLayer         = DataLayer;

            using (Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add class to dataLayer"))
            {
                transaction.Context.ContextInfo.Add("Generated", true);

                string        typeName = newTypeName;
                ClassNameInfo cnh      = new ClassNameInfo(typeName);

                // Si il n'y a pas de namespace, on force le namespace par défaut.
                if (String.IsNullOrEmpty(cnh.Namespace))
                {
                    // Si il y a plusieurs packages, on va lui demander d'en sélectionner un
                    if (modelsLayer.Packages.Count > 1)
                    {
                        NamespacesSelectorDialog dlg = new NamespacesSelectorDialog(modelsLayer.Packages);
                        if (dlg.ShowDialog() == DialogResult.Cancel)
                        {
                            return(null);
                        }
                        cnh.Namespace = dlg.SelectedNamespace;
                    }
                    else
                    {
                        cnh.Namespace = modelsLayer.DefaultPackage.Name;
                    }
                }

                // Recherche si le type existe dans un des packages
                newDefinedTypeModel = modelsLayer.FindType(cnh.Namespace, cnh.ClassName);
                if (newDefinedTypeModel == null)
                {
                    bool classExists;
                    newDefinedTypeModel = modelsLayer.AddTypeIfNotExists(cnh, false, out classExists);
                }

                transaction.Commit();
            }
            return(newDefinedTypeModel);
        }
Example #6
0
        /// <summary>
        /// Sélection d'un modèle
        /// </summary>
        /// <param name="component">The component.</param>
        /// <param name="metaData">The meta data.</param>
        /// <returns></returns>
        bool IModelsMetadata.SelectModel(ExternalComponent component, out ComponentModelMetadata metaData)
        {
            metaData = null;

            // Ici on veut saisir le fichier décrivant le système
            ComponentType?ct = null;

            if (component.MetaData != null)
            {
                ct = component.MetaData.ComponentType;
            }

            RepositoryTreeForm wizard = new RepositoryTreeForm(true, ct);

            if (wizard.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // On doit le créer
                if (wizard.SelectedItem == null)
                {
                    //
                    // Création d'un composant externe
                    //
                    if (component.Name == String.Empty)
                    {
                        PromptBox pb = new PromptBox("Name of the new component");
                        if (pb.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                        {
                            return(false);
                        }

                        // Vérification des doublons.
                        if (_metadatas.NameExists(pb.Value))
                        {
                            IIDEHelper ide = ServiceLocator.Instance.IDEHelper;
                            if (ide != null)
                            {
                                ide.ShowMessage("This model already exists in this model.");
                            }
                            return(false);
                        }

                        component.Name = pb.Value;
                    }

                    // Création d'un modèle vide dans un répertoire temporaire
                    string relativeModelFileName = component.Name + ModelConstants.FileNameExtension;
                    string fn = Utils.GetTemporaryFileName(relativeModelFileName);
                    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fn));

                    // Persistence du modèle
                    CandleModel model = ModelLoader.CreateModel(component.Name, component.Version);
                    component.ModelMoniker = model.Id;
                    SerializationResult result = new SerializationResult();
                    CandleSerializationHelper.Instance.SaveModel(result, model, fn);

                    // Et ouverture du modèle
                    ServiceLocator.Instance.ShellHelper.Solution.DTE.ItemOperations.OpenFile(fn, EnvDTE.Constants.vsViewKindDesigner);
                }
                else // Sinon affectation
                {
                    metaData = wizard.SelectedItem;
                    ExternalComponent externalComponent = component.Model.FindExternalComponent(metaData.Id);
                    if (externalComponent != null)
                    {
                        IIDEHelper ide = ServiceLocator.Instance.IDEHelper;
                        if (ide != null)
                        {
                            ide.ShowMessage("This model already exists in this model.");
                        }
                        return(false);
                    }
                    metaData.UpdateComponent(component);
                }

                return(true); // On ne passe pas dans le rollback
            }
            return(false);
        }