The Artima Developer Community
Sponsored Link

.NET Buzz Forum
Einstellungen einfach speichern und laden

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
-

Posts: 1524
Nickname: nitronic
Registered: Jul, 2006

Norbert Eder works as a software architect.
Einstellungen einfach speichern und laden Posted: Mar 12, 2007 1:58 AM
Reply to this message Reply

This post originated from an RSS feed registered with .NET Buzz by -.
Original Post: Einstellungen einfach speichern und laden
Feed Title: Norbert Eder - Living .NET
Feed URL: http://feeds.feedburner.com/NorbertEder-Livingnet
Feed Description: Copyright (c)2005, 2006 by Norbert Eder
Latest .NET Buzz Posts
Latest .NET Buzz Posts by -
Latest Posts From Norbert Eder - Living .NET

Advertisement
Wer beispielsweise viele unterschiedliche Konfigurationen speichern muss (oder auch andere Daten), dem wird es nicht allzu einfach gemacht. Zum einen bietet sich eine Datenbank an (zusammen mit einem O/R Mapper). Wer keine Datenbank verwenden m��chte (aus unterschiedlichsten Gr��nden), der muss sich anders behelfen. Serialisierung ist eine M��glichkeit. Da ich nun genau diesen Fall hatte, schrieb ich mir einen kleinen Manager der diese Aufgabe f��r mich ��bernimmt.

Implementiert ist die Klasse als Singleton und kann mit allen serialisierbaren Typen umgehen:

/// <summary>
/// Read and write Configuration files. Uses the binary formatter.
/// </summary>
public class ConfigurationManager
{
    #region Private Members

    private static object _lockObject = new object();
    private static ConfigurationManager _instance = null;

    private string _configPath = null;

    #endregion Private Members

    #region Properties

    /// <summary>
    /// ConfigurationPath is used to store the configuration
    /// </summary>
    public string ConfigurationPath
    {
        get { return this._configPath; }
        set { this._configPath = value; }
    }

    #endregion Properties

    #region ctor

    /// <summary>
    /// Private Constructor -> Singleton
    /// </summary>
    private ConfigurationManager() {}

    #endregion ctor

    #region Public Methods

    /// <summary>
    /// Creates a new instance if there wasn't already 
    /// one created, else the available instance will be 
    /// returned
    /// </summary>
    /// <returns>ConfigurationManager instance</returns>
    public static ConfigurationManager GetInstance()
    {
        lock (_lockObject)
        {
            if (_instance == null)
                _instance = new ConfigurationManager();
            return _instance;
        }
    }

    /// <summary>
    /// Read configuration. The typename is used as the filename
    /// </summary>
    /// <typeparam name="T">Any serializable type</typeparam>
    /// <param name="configuration">Serializable object</param>
    /// <returns>Given type T</returns>
    public T Read<T>(T configuration)
    {
        return Read<T>(configuration.GetType().Name);
    }

    /// <summary>
    /// Read configuration
    /// </summary>
    /// <typeparam name="T">Any serializable type</typeparam>
    /// <param name="configuration">Serializable object</param>
    /// <returns>Given type T</returns>
    public T Read<T>(string configuration)
    {
        if (this._configPath == null 
          :: !Directory.Exists(this._configPath))
            throw new Exception(
            String.Format(
            "ConfigurationManager: No valid path given: {0}", 
            this._configPath ?? "<not set>"));

        string filename = 
          Path.Combine(this._configPath, configuration) + ".config";

        if (!File.Exists(filename))
            throw new Exception(
            String.Format(
            "ConfigurationManager: Configuration {0} doesn't exist", 
            filename));

        BinaryFormatter bf = new BinaryFormatter();

        FileStream fs = new FileStream(filename, FileMode.Open);

        T tempObject = (T)bf.Deserialize(fs);

        fs.Close();

        return tempObject;
    }

    /// <summary>
    /// Write Configuration. The typename is used as the filename
    /// </summary>
    /// <typeparam name="T">Any serializable type</typeparam>
    /// <param name="configuration">Serializable object</param>
    public void Write<T>(T configuration)
    {
        this.Write(configuration, configuration.GetType().Name);
    }

    /// <summary>
    /// Write Configuration.
    /// </summary>
    /// <typeparam name="T">Any serializable type</typeparam>
    /// <param name="configuration">Serializable object</param>
    /// <param name="filename">Filename to be used</param>
    public void Write<T>(T configuration, string filename)
    {
        if (this._configPath == null 
          :: !Directory.Exists(this._configPath))
            throw new Exception(
            String.Format(
            "ConfigurationManager: No valid path given: {0}", 
            this._configPath ?? "<not set>"));

        string file = 
          Path.Combine(this._configPath, filename) + ".config";

        BinaryFormatter bf = new BinaryFormatter();

        FileStream fs = 
          new FileStream(file, FileMode.OpenOrCreate);

        bf.Serialize(fs, configuration);

        fs.Close();
    }

    #endregion Public Methods
}

Wie kann dieser Manager nun eingesetzt werden? Zuerst muss ein serialisierbares Objekt erstellt werden:

[Serializable]
public class Package
{
    public string PackagePath = null;
    public ArrayList DirectoryList = new ArrayList();
    public ArrayList FileTypeList = new ArrayList();
    public ArrayList FilesList = new ArrayList();
}

Diese Klasse ist serialisierbar und kann nun mit dem ConfigurationManager verwendet werden. (Der Name ConfigurationManager wird von mir f��r das Speichern von Konfigurationen verwendet. Grundlegend k��nnen alle serialisierbaren Typen damit gespeichert bzw. geladen werden.)

Und so geschieht in weiterer Folge der Aufruf:
ConfigurationManager cm = ConfigurationManager.GetInstance();
cm.ConfigurationPath = "MyPath";

Package pcp = new Package();
pcp.PackagePath = "Another Path";
cm.Write(pcp, "MyFile.config");

Package originalPackage = cm.Read("MyFile.config");

Anzumerken ist, dass der Pfad des ConfigurationManagers nur einmal gesetzt werden muss, also nicht bei jedem Aufruf (ausser die Konfigurationen werden in unterschiedlichen Verzeichnissen abgelegt).

Read: Einstellungen einfach speichern und laden

Topic: Migrating .NET Applications with Mono Previous Topic   Next Topic Topic: ASP.NET Data Tutorial 11: Custom Formatting Based Upon Data (C#)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use