Exemplo n.º 1
0
 /// <summary>
 /// A la fin de la publication, on met à jour les fichiers des infos de l'assemblie avec le
 /// n° de version du modèle.
 /// </summary>
 /// <param name="model"></param>
 /// <param name="modelFileName"></param>
 void IStrategyPublishEvents.OnPublicationEnded(CandleModel model, string modelFileName)
 {
     if (!String.IsNullOrEmpty(T4Template))
     {
         if (model.SoftwareComponent != null)
         {
             // Création du fichier AssemblyInfo
             foreach (AbstractLayer layer in model.SoftwareComponent.Layers)
             {
                 if (layer is SoftwareLayer)
                 {
                     IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();
                     if (shell != null)
                     {
                         // Recherche du projet associé
                         Project prj = shell.FindProjectByName(((SoftwareLayer)layer).VSProjectName);
                         if (prj != null)
                         {
                             Context.Project = prj;
                             CallT4Template(prj, T4Template, layer, _outputFileName);
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Gets a value indicating whether this <see cref="ICommand"/> is visible.
        /// </summary>
        /// <returns></returns>
        /// <value><c>true</c> if visible; otherwise, <c>false</c>.</value>
        public bool Visible()
        {
            IShellHelper sh = ServiceLocator.Instance.GetService <IShellHelper>();

            if (String.IsNullOrEmpty(_fileName))
            {
                return(false);
            }

            if (sh != null)
            {
                // On ne peut pas publier un modèle qui n'est pas le modèle courant
                // sauf si c'est un composant binaire (pour permettre la mise à jour)
                if (_model != null && _model.BinaryComponent != null)
                {
                    return(true);
                }

                // Vérif si c'est le modèle associé à la solution courante
                string currentModel = sh.GetSolutionAssociatedModelName();
                if (currentModel != null && !Utils.StringCompareEquals(_fileName, currentModel))
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 3
0
        protected void ValidateProject(ValidationContext context)
        {
            if (Type != ArtifactType.Project)
            {
                return;
            }

            string msg     = "Assembly name is not valid for the artifact {0} in the layer {1}.";
            bool   isValid = false;

            try
            {
                IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();
                if (shell != null)
                {
                    isValid = shell.FindProjectByAssemblyName(InitialFileName) != null;
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }

            if (!isValid)
            {
                AbstractLayer layer     = LayerHasArtifacts.GetLayer(this);
                string        layerName = layer != null ? layer.Name : "???";
                context.LogError(
                    String.Format(msg, FileName, layerName),
                    "ERRART1", // Unique error number
                    this);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Génération du fichier de config à partir des fichiers de l'utilisateur
        /// </summary>
        /// <param name="layer">The layer.</param>
        /// <param name="project">The project.</param>
        /// <param name="projectFolder">The project folder.</param>
        /// <param name="forceGeneration">if set to <c>true</c> [force generation].</param>
        /// <returns></returns>
        private string GenerateConfigurationFile(Layer layer, Project project, string projectFolder,
                                                 bool forceGeneration)
        {
            if (project == null)
            {
                return(null);
            }

            IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();

            // Vérification si le répertoire de config existe
            string configFolderPath = Path.Combine(projectFolder, ConfigFolderName);

            // On s'assure de son intègration dans la solution
            Directory.CreateDirectory(configFolderPath);
            ProjectItem folder = shell.AddFolderToProject(project.ProjectItems, ConfigFolderName);

            // Création des fichiers à personnaliser

            // D'abord le fichier correspondant au mode courant.
            ConfigurationMode mode            = new ConfigurationMode(project);
            string            currentFileName = CreateCustomConfigurationFile(mode.CurrentMode, configFolderPath, folder);
            // Puis le fichier commun
            string commonFileName = CreateCustomConfigurationFile("Common", configFolderPath, folder);

            if (forceGeneration || File.GetLastWriteTime(commonFileName) > _lastGenerationTime ||
                File.GetLastWriteTime(currentFileName) > _lastGenerationTime)
            {
                // Fichier généré
                string generatedFileName = CalculateApplicationConfigurationFileName(layer);
                if (generatedFileName == null)
                {
                    return(configFolderPath);
                }

                if (project != null && shell != null)
                {
                    // Création d'un fichier xml correspondant à la fusion du fichier commun et
                    // du fichier correspondant au contexte courant (debug, release...)

                    // Merge
                    XmlMerger   merger         = new XmlMerger();
                    XmlDocument customDocument = merger.MergeXml(currentFileName, commonFileName);

                    // Puis merge avec les config du modèle
                    XmlDocument resultDocument = MergeDeclaredConfigurations(customDocument, layer.Component);

                    // Sauvegarde
                    string generatedFilePath = Path.Combine(projectFolder, generatedFileName);
                    Directory.CreateDirectory(Path.GetDirectoryName(generatedFilePath));
                    shell.EnsureCheckout(generatedFilePath);
                    resultDocument.Save(generatedFilePath);
                    shell.AddFileToProject(project, generatedFilePath);
                }
            }
            return(configFolderPath);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Sets the current mode from visual studio context.
        /// </summary>
        private void SetCurrentModeFromVisualStudioContext()
        {
            IShellHelper shell = ServiceLocator.Instance.ShellHelper;

            if (shell != null && shell.Solution != null && shell.Solution.SolutionBuild != null && shell.Solution.SolutionBuild.ActiveConfiguration != null)
            {
                _currentMode = shell.Solution.SolutionBuild.ActiveConfiguration.Name;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Execute the command
        /// </summary>
        public void Exec()
        {
            IShellHelper shell = ServiceLocator.Instance.ShellHelper;

            if (shell != null)
            {
                shell.Navigate(_metadata.DocUrl);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SafeStreamWriter"/> class.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="append">if set to <c>true</c> [append].</param>
        /// <param name="encoding">The encoding.</param>
        public SafeStreamWriter(string path, bool append, Encoding encoding)
        {
            IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();

            if (shell != null)
            {
                shell.EnsureCheckout(path);
            }
            _writer = new StreamWriter(path, append, encoding);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SafeStreamWriter"/> class.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        public SafeStreamWriter(string fileName)
        {
            IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();

            if (shell != null)
            {
                shell.EnsureCheckout(fileName);
            }
            _writer = new StreamWriter(fileName);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates the custom configuration file.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="configFolderPath">The config folder path.</param>
        /// <param name="folder">The folder.</param>
        /// <returns></returns>
        private string CreateCustomConfigurationFile(string name, string configFolderPath, ProjectItem folder)
        {
            IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();
            // Calcule le nom du fichier personnalisable
            string customFileName = String.Concat(name, ".config");
            string customFilePath = Path.Combine(configFolderPath, customFileName);

            XmlDocument xdoc = new XmlDocument();

            // Ajout si n'existe pas
            if (!File.Exists(customFilePath))
            {
                // On regarde si il n'existe pas un template
                bool           fileCreated      = false;
                string         templateFileName = String.Format(_templateFormatName, name);
                RepositoryFile rf =
                    new RepositoryFile(RepositoryCategory.T4Templates, Path.Combine("ConfigFiles", templateFileName));
                try
                {
                    if (rf.Exists())
                    {
                        xdoc.Load(rf.LocalPhysicalPath);
                        fileCreated = true;
                    }
                }
                catch
                {
                }

                // Si on est pas arrivé à en créer un à partir d'un template, on en crée un vide.
                if (!fileCreated)
                {
                    xdoc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?><configuration/>");
                }

                xdoc.Save(customFilePath);
                shell.AddFileToFolder(folder, customFilePath);
            }
            else
            {
                xdoc.Load(customFilePath);
            }
            return(customFilePath);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Génération des fichiers de stratégies
        /// </summary>
        /// <remarks>
        /// </remarks>
        public void Execute()
        {
            // Pour éviter de boucler, on ne regénére pas si la dernière génération s'est faite dans les dernières 2 sec
            TimeSpan ts = DateTime.Now - _lastGenerationTime;

            if (ts.TotalSeconds <= 2)
            {
                return;
            }

            IShellHelper shell = ServiceLocator.Instance.ShellHelper;

            // vérification si la stratégie s'applique sur l'élément courant
            if (Context.GenerationPass != GenerationPass.CodeGeneration || shell == null)
            {
                return;
            }

            if (!(CurrentElement is Layer && ((Layer)CurrentElement).LayerPackage.IsHigherLevel()))
            {
                return;
            }

            try
            {
                _generating = true;
                string configFolderPath =
                    GenerateConfigurationFile(CurrentElement as Layer, Context.Project, Context.ProjectFolder, true);
                // Puis on s'abonne aux events de modif
                if (configFolderPath != null)
                {
                    AdviseFileEvents(configFolderPath);
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
            finally
            {
                _lastGenerationTime = DateTime.Now;
                _generating         = false;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Vérification si la commande peut s'activer
        /// </summary>
        /// <returns></returns>
        /// <value><c>true</c> if visible; otherwise, <c>false</c>.</value>
        public bool Visible()
        {
            // Fichier null
            if (String.IsNullOrEmpty(_fileName))
            {
                return(false);
            }

            // Est on bien sur le modèle de la solution ?
            IShellHelper sh = ServiceLocator.Instance.GetService <IShellHelper>();

            if (sh != null)
            {
                string currentModel = sh.GetSolutionAssociatedModelName();
                if (currentModel != null && !Utils.StringCompareEquals(_fileName, currentModel))
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Recherche le modèle associé à la solution courante
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// Le modèle associé est contenu dans un fichier portant le même nom que la solution
        /// </remarks>
        public static CandleModel GetModelFromCurrentSolution()
        {
            try
            {
                IShellHelper shell = ServiceLocator.Instance.GetService <IShellHelper>();
                if (shell == null)
                {
                    return(null);
                }

                // On cherche d'abord si le nom est enregistré dans la solution
                string candleModelPath = shell.GetSolutionAssociatedModelName();
                if (candleModelPath == null)
                {
                    // Si pas trouvé, on le déduit à partir du nom de la solution
                    string solutionName = (string)shell.Solution.Properties.Item("Name").Value;
                    candleModelPath =
                        System.IO.Path.Combine(shell.SolutionFolder,
                                               String.Concat(solutionName, ModelConstants.FileNameExtension));
                }
                // Recherche dans la RDT
                CandleModel model = GetModelFromCurrentSolution(candleModelPath);
                // Si tjs null, on essaye de le charger directement
                if (model == null)
                {
                    ModelLoader loader = ModelLoader.GetLoader(candleModelPath, true);
                    if (loader != null)
                    {
                        model = loader.Model;
                    }
                }
                return(model);
            }
            catch
            {
            }

            return(null);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Accepts the artifact.
        /// </summary>
        /// <param name="artifact">The artifact.</param>
        private void AcceptArtifact(Artifact artifact)
        {
            if (artifact.Type == ArtifactType.Content && _scope == ReferenceScope.Compilation)
            {
                return;
            }

            if ((artifact.Scope & _scope) != _scope)
            {
                return;
            }

#if DEBUG
            if (_scope == ReferenceScope.Publish)
            {
                if (artifact.Type == ArtifactType.AssemblyInGac && !_initialModelIsInSolution)
                {
                    throw new Exception("cas incorrect");
                }

                if (IsExternalModel && _scope != ReferenceScope.Runtime)
                {
                    throw new Exception("cas incorrect");
                }
            }
#endif
            // Assemblie dans le GAC, on le prend tel quel
            if (artifact.Type == ArtifactType.AssemblyInGac)
            {
                if (_scope == ReferenceScope.Compilation)
                {
                    _references.Add(artifact.FileName);
                }
                return;
            }

            // Une assemblie du framework sélectionné, on résoud son chemin
            if (artifact.Type == ArtifactType.DotNetFramework)
            {
                if (_scope == ReferenceScope.Compilation)
                {
                    CandleModel model = global::DSLFactory.Candle.SystemModel.CandleModel.GetInstance(artifact.Store);
                    _references.Add(
                        DSLFactory.Candle.SystemModel.Utilities.DotNetFrameworkHelper.ResolvePath(model,
                                                                                                  artifact.FileName));
                }
                return;
            }

            //if (artifact.Type == ArtifactType.Assembly)
            //{
            //    //if( parent != null )
            //    references.Add(Path.Combine(LocalPath, artifact.FileName));
            //    //else
            //    //    References.Add( Path.Combine( LatestPath, artifact.FileName ) );
            //    return;
            //}

            // Référence de type projet
            if (artifact.Type == ArtifactType.Project)
            {
                // Si on est dans le projet courant, on recherche le nom de l'assembly
                if (!IsExternalModel && _initialModelIsInSolution)
                {
                    if (_scope == ReferenceScope.Compilation)
                    {
                        _references.Add(artifact.FileName);
                    }
                    else
                    {
                        // Nom de l'assembly du projet
                        IShellHelper shell = ServiceLocator.Instance.ShellHelper;
                        if (shell != null)
                        {
                            EnvDTE.Project project = shell.FindProjectByName(artifact.FileName);
                            if (project != null)
                            {
                                string outputPath =
                                    (string)
                                    project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value;
                                string assemblyName = (string)project.Properties.Item("OutputFileName").Value;
                                _references.Add(
                                    Path.Combine(Path.GetDirectoryName(project.FullName),
                                                 String.Concat(outputPath, assemblyName)));
                            }
                        }
                    }
                }
                else // On est dans un modèle qui ne correspond pas au projet courant
                {
                    if (_scope == ReferenceScope.Runtime)
                    {
                        string fileName = Path.Combine(CurrentModelPath, artifact.InitialFileName);
                        _references.Add(fileName);
                    }
                }

                return;
            }

            // Si on est dans le modèle courant
            if (_initialModelIsInSolution && !IsExternalModel)
            {
                string fileName = Path.Combine(_projectPath.Peek(), artifact.FileName);
                if (!File.Exists(fileName))
                {
                    Utils.CopyFile(artifact.InitialFileName, fileName);
                }

                if (!File.Exists(fileName))
                {
                    fileName = Path.Combine(SolutionFolder, artifact.FileName);
                }
                _references.Add(fileName);
            }
            else
            {
                _references.Add(Path.Combine(_projectPath.Peek(), artifact.FileName));
            }
        }
Exemplo n.º 14
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.º 15
0
 public ChipsetThermometer(IShellHelper shellHelper, string name)
 {
     _shellHelper = shellHelper;
     Name         = name;
 }
Exemplo n.º 16
0
 public SensorFactory(IShellHelper shellHelper)
 {
     _shellHelper = shellHelper;
 }
 public DS18B20Thermometer(IShellHelper shellHelper, SensorSettings settings)
 {
     _shellHelper = shellHelper;
     _deviceId    = settings.DeviceId;
     Name         = settings.Name;
 }
Exemplo n.º 18
0
        /// <summary>
        /// Called when [after save].
        /// </summary>
        /// <param name="docCookie">The doc cookie.</param>
        /// <returns></returns>
        int IVsRunningDocTableEvents.OnAfterSave(uint docCookie)
        {
            if (_generating)
            {
                return(VSConstants.S_OK);
            }

            // Pour éviter de boucler, on ne regénére pas si la dernière génération s'est faite dans les dernières 2 sec
            TimeSpan ts = DateTime.Now - _lastGenerationTime;

            if (ts.TotalSeconds <= 2)
            {
                return(VSConstants.S_OK);
            }

            IVsRunningDocumentTable rdtEvents = GetService <IVsRunningDocumentTable>(typeof(SVsRunningDocumentTable));
            uint         pgrfRDTFlags;
            uint         pdwReadLocks;
            uint         pdwEditLocks;
            string       filePath;
            IVsHierarchy ppHier;
            IntPtr       ppunkDocData;
            uint         itemId;

            if (
                rdtEvents.GetDocumentInfo(docCookie, out pgrfRDTFlags, out pdwReadLocks, out pdwEditLocks, out filePath,
                                          out ppHier, out itemId, out ppunkDocData) == VSConstants.S_OK &&
                filePath != null)
            {
                string folderPath = Path.GetDirectoryName(filePath).ToLower();

                if (!_configFolders.Contains(folderPath) || Path.GetExtension(filePath).ToLower() != ".config")
                {
                    return(VSConstants.S_OK);
                }

                try
                {
                    _generating = true;

                    // TODO recherche le modele à partir d'autre chose que la RDT car il faut que ça marche
                    // même si le modèle n'a pas été ouvert.
                    IShellHelper shell = GetService <IShellHelper>();
                    if (shell != null)
                    {
                        CandleModel model = CandleModel.GetModelFromCurrentSolution();
                        if (model != null && model.SoftwareComponent != null)
                        {
                            foreach (LayerPackage lp in model.SoftwareComponent.LayerPackages)
                            {
                                if (lp.IsHigherLevel())
                                {
                                    foreach (Layer layer in lp.Layers)
                                    {
                                        Project project = shell.FindProjectByName(layer.VSProjectName);
                                        if (project != null)
                                        {
                                            string projectFolder = Path.GetDirectoryName(project.FileName);
                                            GenerateConfigurationFile(layer, project, projectFolder, false);
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    return(VSConstants.S_FALSE);
                }
                finally
                {
                    _lastGenerationTime = DateTime.Now;
                    _generating         = false;
                }
            }

            return(VSConstants.S_OK);
        }