Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês
Esta documentação foi arquivada e não está sendo atualizada.

Serialização e Armazenamento de Documento

Microsoft .NET Framework provides a powerful environment for creating and displaying high quality documents. Enhanced features that support both fixed-documents and flow-documents, advanced viewing controls, combined with powerful 2D and 3D graphic capabilities take .NET Framework applications to a new level of quality and user experience. Being able to flexibly manage an in-memory representation of a document is a key feature of .NET Framework, and being able to efficiently save and load documents from a data store is a need of almost every application. The process of converting a document from an internal in-memory representation to an external data store is termed serialization. The reverse process of reading a data store and recreating the original in-memory instance is termed deserialization.

Este tópico contém as seguintes seções.

Ideally the process of serializing and deserializing a document from and then back into memory is transparent to the application. O aplicativo chama um serializador "gravação" método para salvar o documento, enquanto uma "leitura" de desserialização. método acessa o armazenamento de dados e recria a instância original na memória. The specific format that the data is stored in is generally not a concern of the application as long as the serialize and deserialize process recreates the document back to its original form.

Applications often provide multiple serialization options which allow the user to save documents to different medium or to a different format. Por exemplo, um aplicativo pode oferecer "Salvar como" opções para armazenar um documento para um arquivo de disco, banco de dados ou serviço da web. Similarly, different serializers could store the document in different formats such as in HTML, RTF, XML, XPS, or alternately to a third-party format. To the application, serialization defines an interface that isolates the details of the storage medium within the implementation of each specific serializer. Além de para os benefícios de encapsular os detalhes do armazenamento, o .NET Framework System.Windows.Documents.Serialization APIs fornecem vários outros recursos importantes.

Features of .NET Framework 3.0 Document Serializers

  • Direct access to the high-level document objects (logical tree and visuals) enable efficient storage of paginated content, 2D/3D elements, images, media, hyperlinks, annotations, and other support content.

  • Synchronous and asynchronous operation.

  • Support for plug-in serializers with enhanced capabilities:

    • System-wide access for use by all .NET Framework applications.

    • Simple application plug-in discoverability.

    • Simple deployment, installation, and update for custom third-party plug-ins.

    • User interface support for custom run-time settings and options.

XPS Print Path

O Microsoft .NET Framework XPS caminho de impressão também fornece um mecanismo extensível para escrever documentos por meio de saída de impressão. XPSserve como um formato de arquivo de documento e é o formato de spool de impressão nativo para Windows Vista. XPSdocumentos podem ser enviados diretamente para XPS-impressoras compatíveis, sem a necessidade de conversão em formato intermediário. See the Visão Geral de Impressão for additional information on print path output options and capabilities.

The System.Windows.Documents.Serialization APIs provide support for both plug-in serializers and linked serializers that are installed separately from the application, bind at run time, and are accessed by using the SerializerProvider discovery mechanism. Plug-in serializers offer enhanced benefits for ease of deployment and system-wide use. Linked serializers can also be implemented for partial trust environments such as XAML browser applications (XBAPs) where plug-in serializers are not accessible. Linked serializers, which are based on a derived implementation of the SerializerWriter class, are compiled and linked directly into the application. Both plug-in serializers and linked serializers operate through identical public methods and events which make it easy to use either or both types of serializers in the same application.

Plug-in serializers aid application developers by providing extensibility to new storage designs and file formats without having to code directly for every potential format at build time. Plug-in serializers also benefit third-party developers by providing a standardized means to deploy, install, and update system accessible plug-ins for custom or proprietary file formats.

Using a Plug-in Serializer

Plug-in serializers are simple to use. The SerializerProvider class enumerates a SerializerDescriptor object for each plug-in installed on the system. The IsLoadable property filters the installed plug-ins based on the current configuration and verifies that the serializer can be loaded and used by the application. The SerializerDescriptor also provides other properties, such as DisplayName and DefaultFileExtension, which the application can use to prompt the user in selecting a serializer for an available output format. A default plug-in serializer for XPS is provided with .NET Framework and is always enumerated. After the user selects an output format, the CreateSerializerWriter method is used to create a SerializerWriter for the specific format. The SerializerWriter.Write method can then be called to output the document stream to the data store.

O exemplo a seguir ilustra um aplicativo que usa o SerializerProvider método de "pluginfilefilter" propriedade. PlugInFileFilter enumerates the installed plug-ins and builds a filter string with the available file options for a SaveFileDialog.


// ------------------------ PlugInFileFilter --------------------------
/// <summary>
///   Gets a filter string for installed plug-in serializers.</summary>
/// <remark>
///   PlugInFileFilter is used to set the SaveFileDialog or
///   OpenFileDialog "Filter" property when saving or opening files
///   using plug-in serializers.</remark>
private string PlugInFileFilter
{
    get
    {   // Create a SerializerProvider for accessing plug-in serializers.
        SerializerProvider serializerProvider = new SerializerProvider();
        string filter = "";

        // For each loadable serializer, add its display
        // name and extension to the filter string.
        foreach (SerializerDescriptor serializerDescriptor in
            serializerProvider.InstalledSerializers)
        {
            if (serializerDescriptor.IsLoadable)
            {
                // After the first, separate entries with a "|".
                if (filter.Length > 0)   filter += "|";

                // Add an entry with the plug-in name and extension.
                filter += serializerDescriptor.DisplayName + " (*" +
                    serializerDescriptor.DefaultFileExtension + ")|*" +
                    serializerDescriptor.DefaultFileExtension;
            }
        }

        // Return the filter string of installed plug-in serializers.
        return filter;
    }
}


After an output file name has been selected by the user, the following example illustrates use of the CreateSerializerWriter method to store a given document in a specified format.


// Create a SerializerProvider for accessing plug-in serializers.
SerializerProvider serializerProvider = new SerializerProvider();

// Locate the serializer that matches the fileName extension.
SerializerDescriptor selectedPlugIn = null;
foreach ( SerializerDescriptor serializerDescriptor in
                serializerProvider.InstalledSerializers )
{
    if ( serializerDescriptor.IsLoadable &&
         fileName.EndsWith(serializerDescriptor.DefaultFileExtension) )
    {   // The plug-in serializer and fileName extensions match.
        selectedPlugIn = serializerDescriptor;
        break; // foreach
    }
}

// If a match for a plug-in serializer was found,
// use it to output and store the document.
if (selectedPlugIn != null)
{
    Stream package = File.Create(fileName);
    SerializerWriter serializerWriter =
        serializerProvider.CreateSerializerWriter(selectedPlugIn,
                                                  package);
    IDocumentPaginatorSource idoc =
        flowDocument as IDocumentPaginatorSource;
    serializerWriter.Write(idoc.DocumentPaginator, null);
    package.Close();
    return true;
}


Installing Plug-in Serializers

O SerializerProvider classe fornece a interface de aplicativo de nível superior para a detecção de serializador de plug-in e o acesso. SerializerProvider Localiza e fornece uma lista dos serializadores que estão instalados e acessíveis no sistema de aplicativo. The specifics of the installed serializers are defined through registry settings. Plug-in serializers can be added to the registry by using the RegisterSerializer method; or if .NET Framework is not yet installed, the plug-in installation script can directly set the registry values itself. The UnregisterSerializer method can be used to remove a previously installed plug-in, or the registry settings can be reset similarly by an uninstall script.

Creating a Plug-in Serializer

Both plug-in serializers and linked serializers use the same exposed public methods and events, and similarly can be designed to operate either synchronously or asynchronously. There are three basic steps normally followed to create a plug-in serializer:

  1. Implement and debug the serializer first as a linked serializer. Initially creating the serializer compiled and linked directly in a test application provides full access to breakpoints and other debug services helpful for testing.

  2. Após o serializador é totalmente testado, um ISerializerFactory interface é adicionada ao criar um plug-in. O ISerializerFactory interface permite o acesso total a todos os .NET Framework os objetos que inclui a árvore lógica, UIElement objetos, IDocumentPaginatorSource, e Visual elementos. Additionally ISerializerFactory provides the same synchronous and asynchronous methods and events used by linked serializers. Desde documentos grandes podem levar tempo para saída, operações assíncronas são recomendadas para manter a interação do usuário responsiva e oferecer "Cancelar" Se ocorrer algum problema com o armazenamento de dados de opção.

  3. Após o serializador de plug-in é criado, um script de instalação é implementado para distribuir e instalar (e desinstalar) o plug-in (veja acima, "Instalar o plug-in serializadores").

Mostrar: