Compartilhar via


Salvar dados em arquivos de projeto

Um subtipo de projeto pode salvar e recuperar dados específicos do subtipo no arquivo de projeto. O Managed Package Framework (MPF) fornece duas interfaces para realizar essa tarefa:

  • A IVsBuildPropertyStorage interface permite acessar valores de propriedade da seção MSBuild do arquivo de projeto. Os métodos fornecidos por podem ser chamados por IVsBuildPropertyStorage qualquer usuário sempre que o usuário precisar carregar ou salvar dados relacionados à compilação.

  • O IPersistXMLFragment é usado para persistir dados relacionados à compilação não compilados em XML de forma livre. Os métodos fornecidos por IPersistXMLFragment são chamados pelo Visual Studio sempre que o Visual Studio precisa persistir dados relacionados à não compilação no arquivo de projeto.

    Para obter mais informações sobre como persistir dados relacionados à compilação e não compilação, consulte Persistir dados no arquivo de projeto MSBuild.

  • Chame o SetPropertyValue método para salvar um caminho completo do arquivo de projeto.

    private SpecializedProject project;
    IVsBuildPropertyStorage projectStorage = (IVsBuildPropertyStorage)project;
    string newFullPath = GetNewFullPath();
    // Set a full path of the project file.
    ErrorHandler.ThrowOnFailure(projectStorage.SetPropertyValue(
        "MSBuildProjectDirectory",
        String.Empty,
        (uint)_PersistStorageType.PST_PROJECT_FILE, newFullPath));
    
  • Chame o GetPropertyValue método para recuperar um caminho completo do arquivo de projeto.

    private SpecializedProject project;
    IVsBuildPropertyStorage projectStorage = (IVsBuildPropertyStorage)project;
    string fullPath;
    // Get a full path of the project file.
    ErrorHandler.ThrowOnFailure(projectStorage.GetPropertyValue(
        "MSBuildProjectDirectory",
        String.Empty,
        (uint)_PersistStorageType.PST_PROJECT_FILE, out fullPath));
    
  1. Implemente o método para determinar se um fragmento IsFragmentDirty XML foi alterado desde que foi salvo pela última vez em seu arquivo atual.

    public int IsFragmentDirty(uint storage, out int pfDirty)
    {
        pfDirty = 0;
        switch (storage)
        {
            case (uint)_PersistStorageType.PST_PROJECT_FILE:
            {
                if (isDirty)
                    pfDirty |= 1;
                break;
            }
            case (uint)_PersistStorageType.PST_USER_FILE:
            {
                // We do not store anything in the user file.
                break;
            }
        }
    
        // Forward the call to inner flavor(s)
        if (pfDirty == 0 && innerCfg != null && this.innerCfg is IPersistXMLFragment)
            return ((IPersistXMLFragment)this.innerCfg).IsFragmentDirty(storage, out pfDirty);
    
        return VSConstants.S_OK;
    
    }
    
  2. Implemente o Save método para salvar os dados XML no arquivo de projeto.

    public int Save(ref Guid guidFlavor, uint storage, out string pbstrXMLFragment, int fClearDirty)
    {
        pbstrXMLFragment = null;
    
        if (IsMyFlavorGuid(ref guidFlavor))
        {
            switch (storage)
            {
                case (uint)_PersistStorageType.PST_PROJECT_FILE:
                {
                    // Create XML for our data.
                    XmlDocument doc = new XmlDocument();
                    XmlNode root = doc.CreateElement(this.GetType().Name);
    
                    XmlNode node = doc.CreateElement(targetsTag);
                    node.AppendChild(doc.CreateTextNode(this.TargetsToExecute));
                    root.AppendChild(node);
    
                    node = doc.CreateElement(updateTargetsTag);
                    node.AppendChild(doc.CreateTextNode(this.UpdateTargetList.ToString()));
                    root.AppendChild(node);
    
                    doc.AppendChild(root);
                    // Get XML fragment representing our data
                    pbstrXMLFragment = doc.InnerXml;
    
                    if (fClearDirty != 0)
                        isDirty = false;
                    break;
                }
                case (uint)_PersistStorageType.PST_USER_FILE:
                {
                    // We do not store anything in the user file.
                    break;
                }
            }
        }
    
        // Forward the call to inner flavor(s)
        if (this.innerCfg != null && this.innerCfg is IPersistXMLFragment)
            return ((IPersistXMLFragment)this.innerCfg).Save(ref guidFlavor, storage, out pbstrXMLFragment, fClearDirty);
    
        return VSConstants.S_OK;
    }
    
  1. Implemente o InitNew método para inicializar as propriedades de extensão do projeto e outros dados independentes de compilação. Esse método é chamado se não houver nenhum dado de configuração XML presente no arquivo de projeto.

    public int InitNew(ref Guid guidFlavor, uint storage)
    {
        //Return,if it is our guid.
        if (IsMyFlavorGuid(ref guidFlavor))
            return VSConstants.S_OK;
    
        //Forward the call to inner flavor(s).
        if (this.innerCfg != null && this.innerCfg is IPersistXMLFragment)
            return ((IPersistXMLFragment)this.innerCfg).InitNew(ref guidFlavor, storage);
    
        return VSConstants.S_OK;
    
  2. Implemente o Load método para carregar os dados XML do arquivo de projeto.

    public int Load(ref Guid guidFlavor, uint storage, string pszXMLFragment)
    {
        if (IsMyFlavorGuid(ref guidFlavor))
        {
            switch (storage)
            {
                case (uint)_PersistStorageType.PST_PROJECT_FILE:
                {
                    // Load our data from the XML fragment.
                    XmlDocument doc = new XmlDocument();
                    XmlNode node = doc.CreateElement(this.GetType().Name);
                    node.InnerXml = pszXMLFragment;
                    if (node == null
                        || node.FirstChild == null
                        || node.FirstChild.ChildNodes.Count == 0
                        || node.FirstChild.ChildNodes[0].Name != targetsTag)
                        break;
                    this.TargetsToExecute = node.FirstChild.ChildNodes[0].InnerText;
    
                    if (node.FirstChild.ChildNodes.Count <= 1
                        || node.FirstChild.ChildNodes[1].Name != updateTargetsTag)
                        break;
                    this.UpdateTargetList = bool.Parse(node.FirstChild.ChildNodes[1].InnerText);
                    break;
                }
                case (uint)_PersistStorageType.PST_USER_FILE:
                {
                    // We do not store anything in the user file.
                    break;
                }
            }
        }
    
        // Forward the call to inner flavor(s)
        if (this.innerCfg != null && this.innerCfg is IPersistXMLFragment)
            return ((IPersistXMLFragment)this.innerCfg).Load(ref guidFlavor, storage, pszXMLFragment);
    
        return VSConstants.S_OK;
    }
    

Observação

Todos os exemplos de código fornecidos neste tópico são partes de um exemplo maior em exemplos VSSDK.