Editando App.Config - Web.Config en Tiempo de Ejecución

Fecha: 19/Abr/2004 (4-04-2004)
Autor: Javier Orellana - XaviWare@hotmail.com

.

Los Archivos App.Config y Web.Config son reemplazados en tiempo de ejecución por el archivo "NombreEjecutable.exe.config", utilizaremos la clase System.Configuration.ConfigurationSettngs, para acceder a la sección AppSettings de dicho archivo. Las claves y sus valores son registrados allí de la siguiente forma:

<add key="NombreClave" value="ValorClave" />

La utilidad de esta clase puede ser vista como el reemplazo de las antiguas API's que utilizabamos para manejar los Archivos .INI.
Genere la siguiente clase con el nombre cAppConfig.VB:

'------------------------------------------------------------------------------
'XaviWare - cAppConfig
'Javier Orellana 31-03-2004 16:21 hrs.
'URL: http://www.xaviware.es.vg/
'XaviWare@hotmail.com
'
'Basado en :
'   Runtime Web.config / App.config Editing 
'   By Peter A. Bromberg, Ph.D.
'       http://www.eggheadcafe.com/articles/20030907.asp
'
'   Creating Your Own Dynamic Properties and Preserve Property Settings in Visual Basic .NET
'   By Steve Hoag, Visual Studio Team, Microsoft Corporation, February 2002
'       http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchcreateyourowndynamicpropertiespreservepropertysettingsinvisualbasicnet.asp
'
'------------------------------------------------------------------------------

Imports System
Imports System.Web
Imports System.Xml
Imports System.Configuration
Imports System.Collections
Imports System.Reflection
Imports System.Diagnostics

Public Enum ConfigFileType
    WebConfig
    AppConfig
End Enum

Public Class cAppConfig
    Inherits System.Configuration.AppSettingsReader

    Public docName As String = String.Empty
    Private node As XmlNode = Nothing
    Private _configType As Integer

    Public Property ConfigType() As Integer
        Get
            Return _configType
        End Get
        Set(ByVal Value As Integer)
            _configType = Value
        End Set
    End Property

    Public Function SetValue(ByVal key As String, ByVal value As String) As Boolean
        Dim cfgdoc As New XmlDocument()
        Call loadConfigDoc(cfgdoc)

        node = cfgdoc.SelectSingleNode("//appSettings")
        If node Is Nothing Then
            Throw New System.InvalidOperationException("appSettings section not found")
        End If

        Try
            Dim addElem As XmlElement = CType(node.SelectSingleNode("//add[@key='" + key + "']"), XmlElement)

            If Not addElem Is Nothing Then
                addElem.SetAttribute("value", value)
            Else
                Dim enTry As XmlElement = cfgdoc.CreateElement("add")
                enTry.SetAttribute("key", key)
                enTry.SetAttribute("value", value)
                node.AppendChild(enTry)
            End If
            Call saveConfigDoc(cfgdoc, docName)
            Return True
        Catch
            Return False
        End Try
    End Function

    Private Sub saveConfigDoc(ByVal cfgDoc As XmlDocument, ByVal cfgDocPath As String)
        Try
            Dim writer As XmlTextWriter = New XmlTextWriter(cfgDocPath, Nothing)
            writer.Formatting = Formatting.Indented
            cfgDoc.WriteTo(writer)
            writer.Flush()
            writer.Close()
            Return
        Catch
            Throw
        End Try
    End Sub

    Public Function removeElement(ByVal elementKey As String) As Boolean
        Try
            Dim cfgDoc As XmlDocument = New XmlDocument()
            loadConfigDoc(cfgDoc)
            ' recupero el nodo appSettings
            node = cfgDoc.SelectSingleNode("//appSettings")
            If node Is Nothing Then
                Throw New System.InvalidOperationException("appSettings section not found")
            End If
            ' XPath selecionamos el elemento "add" que contiene la clave a remover
            node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"))

            saveConfigDoc(cfgDoc, docName)
            Return True
        Catch
            Return False
        End Try
    End Function

    Private Function loadConfigDoc(ByVal cfgDoc As XmlDocument) As XmlDocument
        Dim Asm As System.Reflection.Assembly
        ' cargamos el archivo de configuración
        If Convert.ToInt32(ConfigType) = Convert.ToInt32(ConfigFileType.AppConfig) Then
            docName = ((Asm.GetEntryAssembly()).GetName()).Name
            docName += ".exe.config"
        Else
            docName = System.Web.HttpContext.Current.Server.MapPath("web.config")
        End If
        cfgDoc.Load(docName)
        Return cfgDoc
    End Function
End Class

Como Utilizar esta Clase:

Ahora veremos como aplicar esta clase en un aplicación VB.Net;


Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Selecciono el Tipo de Archivo de Configuracion Web/App
        appCfg.ConfigType = Convert.ToInt32(ConfigFileType.AppConfig)

        'Creo la Cadena de Conección
        gstrCnString = ""
        gstrCnString = gstrCnString & "Provider=Microsoft.Jet.OLEDB.4.0;Password='';User ID=Admin;"
        gstrCnString = gstrCnString & "Data Source=" & appCfg.GetValue("PathBase", Type.GetType("System.String")) & ";"
        gstrCnString = gstrCnString & "Mode=Share Deny None;Extended Properties='';Jet OLEDB:System database='';Jet OLEDB:Registry Path='';Jet OLEDB:Database Password='';"
        gstrCnString = gstrCnString & "Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;"
        gstrCnString = gstrCnString & "Jet OLEDB:New Database Password='';Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;"
        gstrCnString = gstrCnString & "Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False&quot;
        ...
		   'Mi Código ...
End Sub

Suponiendo que esta es la carga de mi formulario Principal en una aplicación,
estariamos obteniendo el valor del siguiente elemento dentro de App.Config:

<add key="PathBase" value="C:\Desarrollo\POF\Base\Base.mdb" />

Bueno ahora dejo en sus manos la comprensión de SetValue, y quedo atento a cualquier comentario.

ir al índice

Índice de la sección dedicada a punto NET (en el Guille)