pontoNETpt
A comunidade PontoNetPT está direccionada a todos os programadores que trabalhem com a plataforma .NET.
Ficheiros de parametrização

Para quem utiliza muito ficheiros de configuração para parametrizar os seus programas provavelmente gostaria de poder criar rápidamente uma nova configuração para comandar uma componente nova.

Este método que descrevo não é nada de especial, e provavelmente já é utilizado por vós, mas fica aqui a referência.

1º Passo - Criar o Xsd do ficheiro de configuração.

Para quem não pescar nada de Schemas sugiro fazer primeiro um exemplo do Xml que pretendem e de seguida dar o comando.

> xsd [xmlfile.xml]

O utilitário XSD.EXE vem com o SDK da framework 2.0. (O visual studio 2005 vem com o SDK).

O schema vais permitir duas coisas, criar a classe que serializa e deserializa o XML e validar o ficheiro de input. (sim, apesar de sermos perfeitos com os nossos ficheiros de Xml, quando essa tarefa passa para outra pessoa, a tendencia é a existir erros de preenchimento).

2º Passo - Gerar a classe que serializa e deserializa o Xml.

É bastante simples pois o mesmo utilitário gera a a classe com o seguinte comando.

> xsd [schema.xsd] /classes

3º Passo - À classe gerada juntar a seguinte classe:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Serialization;

    public class XmlUtils<T>
    {
        static public T Deserialize(string filename, string schemaFile)
        {
            if (!File.Exists(filename))
                throw new System.IO.FileNotFoundException(string.Format("Can't find {0} in {1}", filename, Directory.GetCurrentDirectory()));
            if (!File.Exists(schemaFile))
                throw new System.IO.FileNotFoundException(string.Format("Can't find {0} in {1}", schemaFile, Directory.GetCurrentDirectory()));
            // Declare an object variable of the type to be deserialized.
            T obj = default(T);
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(null, schemaFile);
            settings.ValidationType = ValidationType.Schema;
            XmlReader reader = null;
            try
            {
                reader = XmlReader.Create(filename, settings);
                XmlSerializer serializer = new XmlSerializer(typeof(T));

                /* Use the Deserialize method to restore the object's state
                   using data from the XML document. */
                obj = (T)serializer.Deserialize(reader);
                return obj;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }

        static public void Serialize(T obj, string filename)
        {
            Stream writer = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                // Create a FileStream to write with.
                writer = new FileStream(filename, FileMode.Create);
                // Serialize the object, and close the TextWriter
                serializer.Serialize(writer, obj);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
            }
        }
    }

4º Passo - Curtir à brava lendo e escrevendo ficheiros de configuração.

Lendo...

            FileSendConfiguration config = XmlUtils<FileSendConfiguration>.Deserialize("FileSend.xml", @"xsd\FileSendConfiguration.xsd");

Escrevendo...

            Axa.Icm.Xml.XmlUtils<FileSendConfiguration>.Serialize(config, "FileSend.xml");

P.S. Não sei se repararam mas apenas funciona para a framework 2.0

 

 


Posted 11-2-2007 1:35 por João Luis Mil-Homens Freire

Comments

Anonymous wrote re: Ficheiros de parametrização
on 1-7-2009 1:37
Luis,

andaste no mestrado em estratégia no ISCTE em 2000/2001?

Carla
Anonymous wrote re: Ficheiros de parametrização
on 2-7-2009 1:57
Luis,

andaste no mestrado em estratégia no ISCTE em 2000/2001?

Carla

Add a Comment

(requerido)  
(opcional)
(requerido)  
Remember Me?
If you can't read this number refresh your screen
Enter the numbers above:  
Powered by Community Server (Commercial Edition), by Telligent Systems