Hola Jose
Lo que yo hablo uso todo lo que esta en:
namespace System.Configuration
>>>>>Por ende no se integra al Administrador de configuracion. Tendriamos
que implementar la lectura o escritura.
Es transpatente solo especificas el archivo, las secciones, los valores tus
secciones tipadas, lo que sea, se leen y se actualizan en forma
transparente, como si fuera el config por defecto de la aplicación.
Te adjunto un ejemplo complejo, tiene secciones tipadas, pero haces lo que
queres, como si fuera el config de la aplic, sin recurrir a serializacion
externa, ni implementaciones propietarias, lo unico propietario en el
ejemplo son las secciones que son tipadas.
Saludos
Daniel Calvin
El 1 de abril de 2009 9:54, José A. Fernández <[email protected]>escribió:
> Daniel
> Gracias por la aclaración, ya que pensé que estaba claro :)... aquí va.
>
>
> >>>Utilizo esta tecnica de separar algunas secciones del web.config* en
> archivos separados *
> Tema1: web.config separado en archivos mediante los
> atributos configSource de algunas secciones. Es decir separamos secciones
> Algo asi
> <appSettings configSource="Web.AppSettings.config"></appSettings>
> y en el archivo Web.AppSettings.config seria algo asi
> <?xml version="1.0" encoding="utf-8" ?>
> <appSettings>
> <add key="ejemplo" value="valor" />
> </appSettings>
>
> Esto se sigue siendo el web.config, así que seguimos utilizando
> la sección appSettings de modo "transparente" (somo si estuviera dentro)
>
>
> Estoy mirando que Carlos utiliza el atributo file en vez de configSource debe
> ser por eso que lo integra al momento de guardar y no mantiene el
>
>
> >>>No creo que la solucion sea como dice Daniel, *porque si es un archivo
> separado* del web.config ....
> Tema 2: archivos de configuracion independiente del web.config, aqui no
> separamos secciones sino que creamos nuestros propios archivos de
> configuracion
> Aqui no estamos utilizando web.config, sino nuestro archivo. Por ende no se
> integra al Administrador de configuracion. Tendriamos que implementar la
> lectura o escritura.
>
>
> Como dices podemos implementar nuestras propias secciones en el web.cofig,
> o nuestros propios archivos de configuracion. Pero estando dentro del
> web.config (inline o enlazando en uno externo con configSource) es de
> "fácil acceso".
> Otra posibilidad seria utilizar Enterprise Library , tiene un AppBlock que
> nos resuelve este mecanismo.
> Tengo también estas opciones utilizando Enterprise Library con archivos
> fisicos o incluso configuracion guardada en el SQL Server
> (con SqlConfigurationSource) ...que lo que hace es idem a un archivo o sea
> serializa la seccion en xml pero guarda en la DB :)
>
>
> Saludos
> _______________________
> Jose A. Fernandez blog: http://geeks.ms/blogs/fernandezja
>
>
>
> 2009/4/1 Daniel Calvin <[email protected]>
>
>> Hola Jose
>>
>> No entiendo, decis:
>>
>> >>>Utilizo esta tecnica de separar algunas secciones del web.config* en
>> archivos separados *
>>
>> Luego decis:
>> >>>No creo que la solucion sea como dice Daniel, *porque si es un archivo
>> separado* del web.config ....
>>
>> Cual es la dif entre lo que decis vos y digo yo?, porque la complejidad
>> agregada es la misma.
>>
>> Si coincido que es mas cómodo meter todo en el config de la aplicación y
>> listo.
>> Cuando hablo de impelmentar cosas me refiero a las las clases que
>> representan las distintas secciones, eso es lo mismo para el config que
>> decidas usar o simplemente te arreglas con los key value y listop.
>>
>> Daniel
>>
>>
>>
>> El 1 de abril de 2009 8:28, José A. Fernández
>> <[email protected]>escribió:
>>
>> Hola Carlos
>>> Utilizo esta tecnica de separar algunas secciones del web.config en
>>> archivos separados pero no los modifico desde la app, asi que no conocia de
>>> este comportamiento (que lo probare cuando tenga un tiempo, ya que debe ser
>>> algun parametro para la actualizacion del contenido en archivos separados)
>>>
>>> Lo que se me ocurre ahora es que debes abrir el archivo Terms.BR.config
>>> directamente y obtener la seccion appSettings y manipularla. No creo que la
>>> solucion sea como dice Daniel, porque si es un archivo separado del
>>> web.config en toda la aplicacion tendremos que hacer nuestra propia tecnica
>>> para leer los datos/obtener y en cambio si es <appSettings file=”
>>> Terms.BR.config”> de esta forma el ConfigurationManager lo tendremos siempre
>>> disponible sin necesidad de implementar nada (por esto me suena raro que
>>> para actualizar "copie" y debamos cambiar el modo de obtenerlo)
>>> Pero bueno la solucion "express" podria venir de la mano de algo asi:
>>>
>>> Dim webConfig As Configuration =
>>> WebConfigurationManager.OpenWebConfiguration("~/Terms.BR.config")
>>> Dim seccion As AppSettingsSection =
>>> CType(webConfig.GetSection("system.web/pages"), AppSettingsSection )
>>> ...y alli manipulas el contenido y lo guardas.
>>> ...te puede ayudar este articulo:
>>> - Acceder a propiedades/atributos de secciones del web.config mediante
>>> codebehind
>>>
>>> http://geeks.ms/blogs/fernandezja/archive/2008/07/29/acceder-a-propiedades-atributos-de-secciones-del-web-config-mediante-codebehind.aspx
>>>
>>>
>>>
>>> Espero que te sirva de ayuda o guia
>>> _______________________
>>> Jose A. Fernandez blog: http://geeks.ms/blogs/fernandezja
>>>
>>>
>>>
>>> 2009/3/31 Carlos Marcelo Santos <[email protected]>
>>>
>>>> Muchas Gracias Diego y Daniel.
>>>>
>>>>
>>>>
>>>> Carlos Marcelo Santos.
>>>>
>>>>
>>>>
>>>> *From:* [email protected] [mailto:[email protected]] *On Behalf Of
>>>> *Daniel Calvin
>>>> *Sent:* Martes, 31 de Marzo de 2009 11:45 a.m.
>>>>
>>>> *To:* [email protected]
>>>> *Subject:* [puntonet] app.config
>>>>
>>>>
>>>>
>>>> Net ya trae clases para eso y podes hace implementaciones propias.
>>>>
>>>> Podes guardar tu propio archivo de conf.
>>>>
>>>> Carlos fijate como se maneja en coop el lazyload.config, usa esas clases
>>>> y algunas propias. Pero todo lo hace con las apis de conf de net.
>>>>
>>>> Daniel
>>>>
>>>> El 31 de marzo de 2009 11:31, Diego Jancic <[email protected]> escribió:
>>>>
>>>> Hola Carlos,
>>>>
>>>> Nunca lo hice, pero imagino que es asi por diseño o por error...
>>>> No pensaste directamente hacer un workarround guardando las
>>>> configuracion en un XML tuyo? Es muy facil hacer una clase con las
>>>> propiedades que queres y serializarlo a XML...
>>>>
>>>> Saludos!
>>>>
>>>> 2009/3/31 Carlos Marcelo Santos <[email protected]>:
>>>>
>>>> > Hola Gente:
>>>> >
>>>> > Disculpen que insista con el tema del mail que copio debajo, ¿alguien
>>>> sabe
>>>> > que puede estar sucediendo?
>>>> >
>>>> >
>>>> >
>>>> > Muchas Gracias.
>>>> >
>>>> >
>>>> >
>>>> > Carlos Marcelo Santos.
>>>> >
>>>> >
>>>> >
>>>> > From: [email protected] [mailto:[email protected]] On Behalf Of
>>>> Carlos
>>>> > Marcelo Santos
>>>> > Sent: Jueves, 26 de Marzo de 2009 12:29 p.m.
>>>> > To: [email protected]
>>>> > Subject: [puntonet] app.config
>>>> >
>>>> >
>>>> >
>>>> > Hola Lista:
>>>> >
>>>> > Tengo una aplicación desktop en la que uso el app.config para
>>>> almacenar
>>>> > valores de configuración entre los tags <appSettings></appSettings>
>>>> >
>>>> > Como necesito implementar multilanguaje extiendo el archivo app.config
>>>> > usando el tag <appSettings> de la siguiente forma:
>>>> >
>>>> > <appSettings file=” Terms.BR.config”>
>>>> >
>>>> > Y cambiando el atributo de file, con un archivo XML bien definido
>>>> cambio de
>>>> > lenguaje sin problemas.
>>>> >
>>>> > Hasta acá todo anda bien.
>>>> >
>>>> > Mi problema se da cuando desde la ejecución del programa cambio algún
>>>> > parámetro, al persistirlo en el app.config con:
>>>> >
>>>> >
>>>> >
>>>> > Dim mAppConfig As System.Configuration. Configuration =
>>>> > ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
>>>> >
>>>> > mAppConfig.AppSettings.Item(“ItemConfig”).Value = “NuevoValor”
>>>> >
>>>> > mAppConfig.Save(ConfigurationSaveMode.Modified)
>>>> >
>>>> >
>>>> >
>>>> > Al ejecutar mAppConfig.Save me copia todo el contenido de
>>>> “Terms.BR.config”
>>>> > en el app.config
>>>> >
>>>> > ¿Conocen alguna forma de impedir que esta copia se produzca?
>>>> >
>>>> >
>>>> >
>>>> > Muchas Gracias.
>>>> >
>>>> >
>>>> >
>>>> > Carlos Marcelo Santos.
>>>> >
>>>> >
>>>> >
>>>> > Se certificó que el correo entrante no contiene virus.
>>>> > Comprobada por AVG - www.avg.es
>>>> > Versión: 8.5.278 / Base de datos de virus: 270.11.28/2022 - Fecha de
>>>> la
>>>> > versión: 03/25/09 18:54:00
>>>>
>>>>
>>>>
>>>>
>>>> --
>>>> Daniel A. Calvin
>>>> Cooperator Team Member
>>>> http://www.cooperator.com.ar
>>>> Microsoft Certified Professional
>>>>
>>>> Se certificó que el correo entrante no contiene virus.
>>>> Comprobada por AVG - www.avg.es
>>>> Versión: 8.5.285 / Base de datos de virus: 270.11.32/2030 - Fecha de la
>>>> versión: 03/31/09 06:02:00
>>>>
>>>>
>>>
>>>
>>>
>>
>>
>> --
>> Daniel A. Calvin
>> Cooperator Team Member
>> http://www.cooperator.com.ar
>> Microsoft Certified Professional
>>
>
>
>
>
--
Daniel A. Calvin
Cooperator Team Member
http://www.cooperator.com.ar
Microsoft Certified Professional
/*-
* Copyright (c) 2006-2007 Eugenio Serrano, Daniel Calvin.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of copyright holders nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR
CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
namespace Cooperator.Framework.Core.LazyLoad
{
public class Provider : ConfigurationElement
{
internal Provider() { }
internal Provider(string entityName)
: this()
{
this["entityname"] = entityName;
}
internal Provider(string entityName, string assemblyName)
: this(entityName)
{
this["assemblyname"] = assemblyName;
}
public
Provider(string entityName, string assemblyName, string className)
: this(entityName, assemblyName)
{
this["classname"] = className;
}
[ConfigurationProperty("entityname", IsKey = true, IsRequired = true)]
public string EntityName { get { return (string)this["entityname"]; }
set { this["entityname"] = value; } }
[ConfigurationProperty("classname", IsRequired = true)]
public string ClassName { get { return (string)this["classname"]; } set
{ this["classname"] = value; } }
[ConfigurationProperty("assemblyname", IsRequired = true)]
public string AssemblyName { get { return (string)this["assemblyname"];
} set { this["assemblyname"] = value; } }
}
public class ProvidersCollection : ConfigurationElementCollection
{
protected internal ProvidersCollection()
{
}
public override
ConfigurationElementCollectionType CollectionType
{
get
{
return
ConfigurationElementCollectionType.AddRemoveClearMap;
}
}
protected override
ConfigurationElement CreateNewElement()
{
return new Provider();
}
protected override
ConfigurationElement CreateNewElement(
string elementName)
{
return new Provider(elementName);
}
protected override Object
GetElementKey(ConfigurationElement element)
{
return string.Format("{0}", ((Provider)element).EntityName);
}
public new string AddElementName
{
get
{ return base.AddElementName; }
set
{ base.AddElementName = value; }
}
public new string ClearElementName
{
get
{ return base.ClearElementName; }
set
{ base.AddElementName = value; }
}
public new string RemoveElementName
{
get
{ return base.RemoveElementName; }
}
public new int Count
{
get { return base.Count; }
}
public Provider this[int index]
{
get
{
return (Provider)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
new public Provider this[string Name]
{
get
{
return (Provider)BaseGet(Name);
}
}
public int IndexOf(Provider psh)
{
return BaseIndexOf(psh);
}
public void Add(Provider psh)
{
BaseAdd(psh);
}
protected override void
BaseAdd(ConfigurationElement element)
{
BaseAdd(element, true);
}
public void Remove(Provider psh)
{
if (BaseIndexOf(psh) >= 0)
BaseRemove(psh.EntityName);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
BaseRemove(name);
}
public void Clear()
{
BaseClear();
}
}
public class ProvidersSection : ConfigurationSection
{
protected internal ProvidersSection()
{
}
[ConfigurationProperty("providers",
IsDefaultCollection = false)]
public ProvidersCollection Providers
{
get
{
ProvidersCollection providers =
(ProvidersCollection)base["providers"];
return providers;
}
}
protected override void DeserializeSection(
System.Xml.XmlReader reader)
{
base.DeserializeSection(reader);
}
protected override string SerializeSection(
ConfigurationElement parentElement,
string name, ConfigurationSaveMode saveMode)
{
string s =
base.SerializeSection(parentElement,
name, saveMode);
return s;
}
}
public static class LazyConfigurationHelper
{
private static ProvidersSection providers;
public static ProvidersSection ProvidersSection { get { return
providers; } }
public static bool Read()
{
return Read(GetFileName());
}
public static bool Read(string fileName)
{
ConfigurationSectionGroup csg = null;
ConfigurationSection cs = null;
Configuration cfg = GetConfiguration(fileName);
if (cfg.HasFile)
{
csg = cfg.SectionGroups["LazyLoad"];
if (csg != null)
{
cs =
cfg.SectionGroups["LazyLoad"].Sections["ProvidersSection"];
if (cs != null)
providers =
cfg.SectionGroups["LazyLoad"].Sections["ProvidersSection"] as ProvidersSection;
return true;
}
else
return false;
}
else
return false;
}
public static void CreateEmpty()
{
CreateEmpty(GetFileName());
}
public static void CreateEmpty(string fileName)
{
Configuration cfg = GetConfiguration(fileName);
cfg.SectionGroups.Remove("LazyLoad");
ProvidersSection lps = new ProvidersSection();
lps.Providers.Add(new Provider("Provider1", "miAssembly",
"myProvider01"));
lps.Providers.Add(new Provider("Provider2", "miAssembly",
"myProvider02"));
lps.Providers.Add(new Provider("Provider3", "miAssembly",
"MyProvider03"));
cfg.SectionGroups.Add("LazyLoad", new ConfigurationSectionGroup());
cfg.SectionGroups["LazyLoad"].Sections.Add("ProvidersSection", lps);
cfg.Save(ConfigurationSaveMode.Full);
}
private static Configuration GetConfiguration(string fileName)
{
Configuration cfg = ConfigurationManager.OpenMappedExeConfiguration(
GetExeConfigurationFileMap(fileName),
ConfigurationUserLevel.None);
return cfg;
}
private static string GetFileName()
{
return GetFileName(null);
}
private static string GetFileName(string fileName)
{
if (fileName == null || fileName.Trim().Length == 0)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string file = AppDomain.CurrentDomain.FriendlyName;
fileName = string.Format("{0}{1}.config", path, file);
}
return fileName;
}
private static ExeConfigurationFileMap
GetExeConfigurationFileMap(string fileName)
{
ExeConfigurationFileMap eCnfFile = new ExeConfigurationFileMap();
eCnfFile.ExeConfigFilename = fileName;
return eCnfFile;
}
}
}