 |
|
 |
Hi, I develop a Xml Configuration plugin for CCNet. It helps you to create custom app.config files for your Development, Test and Production environments...
Please check out: http://sourceforge.net/projects/dotnethelper/[^]
Regards...
modified on Saturday, April 16, 2011 1:34 PM
|
|
|
|
 |
|
 |
Hi,
I used the code that you supplied. Thanks very much, it saved me alot of work.
Johannekie
|
|
|
|
 |
|
 |
I had to adjust a few things in order to get it to function the way I wanted it to, but you provided an excellent basis!!
|
|
|
|
 |
|
 |
My problem is the following: I have many projects in a solution, each project has a file AppConfig . I need to load all configuration data of the all project's solution on memory cache. How can i do this? Can you help me please?
|
|
|
|
 |
|
 |
My problem is the following: I have many projects in a solution, each project has a file AppConfig. I need to load all configuration data of the all project's solution on memory cache. How can i do this? Can you help me please?
|
|
|
|
 |
|
 |
I guess my question is similar to another thread around multiple sections.
I'm attempting to create multiple instances of the ConfigOpt object, to collect say general application configuration data, with a second instance for other data. When doing this, data seems to report to the instance initailised last, regardless of the object name.
For example,
Dim objConfig As New ConfigOpt 'for application settings
Dim objProjectData As New ConfigOpt 'for other data
'instance 1
objConfig.Initialize(gstrConfigFile)
objConfig.SetOption("Param1","mydata")
objConfig.Store
'instance 2
objProjectData.Initialize(gstrProjectDataFile)
objProjectData.SetOption("Param2","mydata2")
objProjectData.Store
'now returning to instance 1
objConfig.SetOption("Param3","mydata3")
objConfig.Store
The above code seems to store mydata3 in the .xml file initialised under objProjectData, rather than objConfig.
Am I attempting something that is simply not possible? - Please help.
|
|
|
|
 |
|
 |
Well... the problem simply is that you're instantiating multiple times a class designed to be used only once.
Notice, in my examples of use, the absence of instantiation (no "New" at all) and the use of the class name instead of instance names.
To achieve your goal, you need to:
1) convert all static (shared) members of the ConfigOpt class in non-static members, by removing the "Shared" keyword from these lines:
Private Shared DSoptions As DataSet
Private Shared mConfigFileName As String
Public Shared ReadOnly Property ConfigFileName() As String
Public Shared Sub Initialize(ByVal ConfigFile As String)
Public Shared Sub Store()
Public Shared Sub Store(ByVal ConfigFile As String)
Public Shared Function GetOption(ByVal OptionName As String) As String
Public Shared Sub SetOption(ByVal OptionName As String, ByVal OptionValue As String)
In this way, all instances will use their own members, so their own config files and DataSets (instead of sharing them, with the side effects you noticed on a shared DSoptions DataSet and a shared mConfigFileName filename).
2) use your code exactly as you wrote it.
Please let me know if you have further problems.
Cheers, AV
|
|
|
|
 |
|
 |
using System.IO;
using System.Data;
///
/// Class for managing configuration persistence adapted from source code at
/// http://www.codeproject.com/vb/net/ConfigOpt.asp#xx1433090xx This class
/// allows setting custom sections much as ini file calls and registry calls do.
///
public class CConfigSettings
{
///
/// This DataSet is used as a memory data structure to hold config
/// section/key/value pairs Inside this DataSet, a DataTable for each
/// section is created
///
private DataSet m_dsOptions;
// This is the filename for the DataSet XML serialization
private string m_szConfigFileName;
///
/// This property is read-only, because it is set through Initialize or
/// Store methods
///
public string szConfigFileName
{
get
{
return m_szConfigFileName;
}
}
///
/// This method has to be invoked before using any other method of
/// ConfigOpt class ConfigFile parameter is the name of the config file
/// to be read. If the config file does not exist, and the user calls
/// "SetOptions", the config file will be created when "Store" is
/// called.
///
///
public void Initialize(string szConfigFile)
{
this.m_szConfigFileName = szConfigFile;
this.m_dsOptions = new DataSet("ConfigOpt");
if(File.Exists(szConfigFile))
{
// If the specified config file exists, it is read to populate
// the DataSet
this.m_dsOptions.ReadXml(szConfigFile);
}
}
///
/// This method serializes the memory data structure holding the config
/// parameters The filename used is the one defined calling Initialize
/// method
///
public void Store()
{
this.Store(this.m_szConfigFileName);
}
///
/// Same as Store() method, but with the ability to serialize on
/// different filename
///
///
public void Store(string szConfigFile)
{
this.m_szConfigFileName = szConfigFile;
this.m_dsOptions.WriteXml(szConfigFile);
}
///
/// Read a configuration Value, given its name and section name
/// (szOptionName). If the Key is not defined, the default value is
/// returned, and the entry is added to the data set.
///
///
///
///
/// string
public string GetOption(string szSectionName, string szOptionName,
string szDefault)
{
bool bAddOption = true;
string szReturn = szDefault;
if (this.m_dsOptions.Tables[szSectionName] != null)
{
DataView dv = m_dsOptions.Tables[szSectionName].DefaultView;
dv.RowFilter = "OptionName='" + szOptionName + "'";
if (dv.Count > 0)
{
szReturn = dv[0]["OptionValue"].ToString();
bAddOption = false;
}
}
if (bAddOption == true)
{
this.SetOption(szSectionName, szOptionName, szDefault);
}
return szReturn;
}
///
/// Overload for getting integer values
///
///
///
///
/// int
public int GetOption(string szSectionName, string szOptionName,
int iDefault)
{
return int.Parse(this.GetOption(szSectionName, szOptionName,
iDefault.ToString()));
}
///
/// Overload for getting double values
///
///
///
///
///
public double GetOption(string szSectionName, string szOptionName,
double dDefault)
{
return double.Parse(this.GetOption(szSectionName, szOptionName,
dDefault.ToString()));
}
///
/// Write in the memory data structure a Key/Value pair for a
/// configuration setting. If the Key already exists, the Value is
/// simply updated, else the Key/Value pair is added. Warning: to update
/// the written Key/Value pair on the config file, you need to call
/// Store
///
///
///
///
public void SetOption(string szSectionName, string szOptionName,
string szOptionValue)
{
if( this.m_dsOptions.Tables[szSectionName] == null)
{
DataTable dt = new DataTable(szSectionName);
dt.Columns.Add("OptionName", System.Type.GetType("System.String"));
dt.Columns.Add("OptionValue", System.Type.GetType("System.String"));
// dt.Columns.Add("OptionType",
this.m_dsOptions.Tables.Add(dt);
}
DataView dv = this.m_dsOptions.Tables[szSectionName].DefaultView;
dv.RowFilter = "OptionName='" + szOptionName + "'";
if( dv.Count > 0)
{
dv[0]["OptionValue"] = szOptionValue;
}
else
{
DataRow dr = m_dsOptions.Tables[szSectionName].NewRow();
dr["OptionName"] = szOptionName;
dr["OptionValue"] = szOptionValue;
this.m_dsOptions.Tables[szSectionName].Rows.Add(dr);
}
}
///
/// Overload of SetOption that takes an integer option value
///
///
///
///
public void SetOption(string szSectionName, string szOptionName,
int iOptionValue)
{
this.SetOption(szSectionName, szOptionName, iOptionValue.
ToString());
}
///
/// Overload of SetOption that takes a double option value
///
///
///
///
public void SetOption(string szSectionName, string szOptionName,
double dOptionValue)
{
this.SetOption(szSectionName, szOptionName, dOptionValue.
ToString());
}
}
|
|
|
|
 |
|
 |
hi,
i wrote this code for my use and practice. use it widely!
using System;
using System.Xml;
using System.Data;
namespace Settings
{
///
/// Summary description for Xml.
///
public class Xml
{
private Xml(){}
private static bool flagInitialized = false;
private static DataSet dataSet = new DataSet();
public static bool Initialize(string xmlPath)
{
try
{
dataSet.ReadXml(xmlPath);
flagInitialized = true;
return flagInitialized;
}
catch(Exception e)
{
throw e;
}
}
public static string GetElement(string elemetName)
{
if (!flagInitialized)
{
return null;
}
DataView dv = dataSet.Tables[elemetName].DefaultView;
if (dv.Count > 0)
{
return dv[0].Row.ItemArray[0].ToString();
}
else
{
return null;
}
}
}
}
Oz R.
|
|
|
|
 |
|
 |
'Add this in you Initialize procedure
Dim aFileStream As New FileStream(ConfigFile, FileMode.Open)
Dim aStreamReader As New StreamReader(aFileStream)
Dim aUE As New UnicodeEncoding
Dim key() As Byte = aUE.GetBytes("password")
Dim RMCrypto As RijndaelManaged = New RijndaelManaged
Dim aCryptoStream As New CryptoStream(aFileStream, _
RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read)
DSoptions.ReadXml(aCryptoStream)
aStreamReader.Close()
aFileStream.Close()
'Add this in your "store" procedure
Dim aXmlTextWriter As Xml.XmlTextWriter
aXmlTextWriter = New XmlTextWriter(ConfigFile, System.Text.Encoding.UTF8)
Dim aUE As New UnicodeEncoding
Dim key() As Byte = aUE.GetBytes("password")
Dim RMCrypto As RijndaelManaged = New RijndaelManaged
Dim aCryptoStream As New CryptoStream(aXmlTextWriter.BaseStream, _
RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write)
DSoptions.WriteXml(aCryptoStream)
aCryptoStream.Close()
DSoptions.Clear()
|
|
|
|
 |
|
 |
Is it possible to have multiple sections (nodes) within the same configuration file?
AN
|
|
|
|
 |
|
 |
Sure, you just have to generalize the ConfigValues DataTable concept, extending (for example) the configuration DataSet so that it holds more configuration DataTables.
Another way could be: adding a "section" column to the key-value combination, implementing then a Select search of the desired value inside the only ConfigValues DataTable.
AV
|
|
|
|
 |
|
|
 |
|
 |
I didn't try that code, but - as far as I see by reading it - it simply seems to make my class compliant with the standard .NET structure for configuration files (that is: AppSettings mechanism, based on an XML with "add" nodes containing key/value pairs as attributes).
I think it doesn't support multiple sections (as mine doesn't), just bacause the Function GetOption(ByVal OptionName As String) method doesn't accept any kind of "section" parameter.
Did you think about "simulating" configuration sections just by adopting a particular naming convention for the stored keys?
For example, you could simply call:
txtMyTextbox.Text = ConfigOpt.GetOption("MySection.txtMyTextbox")
instead of:
txtMyTextbox.Text = ConfigOpt.GetOption("txtMyTextbox")
Ok: this "workaround" doesn't guarantee that keys of the same section are stored as a "set" in the configuration file, but - from the application perspective - you actually can have "homologous" keys in different "sections".
AV
|
|
|
|
 |
|
 |
What would be the format of a file with multiple configuration sections that ReadXml can read and put in the options DataSet?
AN
|
|
|
|
 |
|
 |
Hi,
This article solves a common problem with the .NET applications but when adopting this, I found it created a lot more problems for me. I work in a team on a fairly large project. We've used the .NET configuration settings widely because of its integration with the IDE and dynamic properties in the designers. A major shortcoming of this implementation, I found is its use of a different XML schema. This breaks our existing code. I have modified the source to use the existing .NET configuration file and I think others may find the source useful. It preserves other contents of the configuration file such as the custom sections and section groups. Please find the code below:
Imports System.IO
Imports System.Xml
' Class for managing configuration persistence
Public Class ConfigOpt
' This DataSet is used as a memory data
' structure to hold config key/value pairs
' Inside this DataSet, a single DataTable named ConfigValues is created
Private Shared DSoptions As DataSet
' This is the filename for the DataSet XML serialization
Private Shared mConfigFileName As String
' This property is read-only, because it is set
' through Initialize or Store methods
Public Shared ReadOnly Property ConfigFileName() As String
Get
Return mConfigFileName
End Get
End Property
' This method has to be invoked before using
' any other method of ConfigOpt class
' ConfigFile parameter is the name of the config file to be read
' (if that file doesn't exists, the method
' simply initialize the data structure
' and the ConfigFileName property)
Public Shared Sub Initialize(ByVal ConfigFile As String)
mConfigFileName = ConfigFile
DSoptions = New DataSet("configuration")
If File.Exists(ConfigFile) Then
' If the specified config file exists,
' it is read to populate the DataSet
DSoptions.ReadXml(ConfigFile)
'Dim dt As DataTable
'For Each dt In DSoptions.Tables
' Console.WriteLine(dt.TableName)
'Next
Else
Dim dt As New DataTable("add")
dt.Columns.Add("key", System.Type.GetType("System.String"))
dt.Columns.Add("value", System.Type.GetType("System.String"))
dt.Columns("key").ColumnMapping = MappingType.Attribute
dt.Columns("value").ColumnMapping = MappingType.Attribute
DSoptions.Tables.Add(dt)
End If
End Sub
' This method serializes the memory data
' structure holding the config parameters
' The filename used is the one defined calling Initialize method
Public Shared Sub Store()
Store(mConfigFileName)
End Sub
' Same as Store() method, but with the ability
' to serialize on a different filename
Public Shared Sub Store(ByVal ConfigFile As String)
mConfigFileName = ConfigFile
DSoptions.WriteXml(ConfigFile)
'post process to collect all add records in configuration/appSettings
If postProcess Then
Dim xdoc As New XmlDocument
xdoc.Load(ConfigFile)
Dim xn As XmlNode
Dim xnAdd As XmlNodeList = xdoc.DocumentElement.SelectNodes("add")
Dim xnAppSett As XmlNode = xdoc.DocumentElement.SelectSingleNode("appSettings")
For Each xn In xnAdd
xdoc.DocumentElement.RemoveChild(xn)
xnAppSett.AppendChild(xn)
Next
xdoc.Save(ConfigFile)
End If
End Sub
' Read a configuration Value (aka OptionValue),
' given its Key (aka OptionName)
' If the Key is not defined, an empty string is returned
Public Shared Function GetOption(ByVal OptionName As String) As String
Dim dv As DataView = DSoptions.Tables("add").DefaultView
dv.RowFilter = "key='" & OptionName & "'"
If dv.Count > 0 Then
Return CStr(dv.Item(0).Item("value"))
Else
Return ""
End If
End Function
' Write in the memory data structure a Key/Value
' pair for a configuration setting
' If the Key already exists, the Value is simply updated,
' else the Key/Value pair is added
' Warning: to update the written Key/Value pair
' on the config file, you need to call Store
Private Shared postProcess As Boolean = False
Public Shared Sub SetOption(ByVal OptionName _
As String, ByVal OptionValue As String, Optional ByVal noadd As Boolean = False)
Dim dv As DataView = DSoptions.Tables("add").DefaultView
dv.RowFilter = "key='" & OptionName & "'"
If dv.Count > 0 Then
dv.Item(0).Item("value") = OptionValue
Else
Dim dr As DataRow = DSoptions.Tables("add").NewRow()
dr("key") = OptionName
dr("value") = OptionValue
DSoptions.Tables("add").Rows.Add(dr)
postProcess = True
End If
End Sub
End Class
In order to determine the name and location of the config file, I've used:
Dim Asm As System.Reflection.Assembly = System.Reflection.Assembly.GetEntryAssembly
ConfigOpt.Initialize(Asm.Location + ".config")
I hope this is helpful.
|
|
|
|
 |
|
 |
The ConfigOpt class was created as an alternative to config files, not having in mind any goal of compatibility with standard .NET configuration files.
So... I can only give you many thanks to this your intervention, that makes the article more complete.
Nice work!
AV
|
|
|
|
 |
|
 |
Your problem may be solve on:
http://idmnetcontrols.com
You try download Config Manager (GUI application) and Configuration Assemblies for using inside of your application.
|
|
|
|
 |
|
 |
Hey,
I'm using the class in a program I've written. From the application I've written, users can open files for editing (the details of these files is irrelevant i think). What I have noticed is that when you open a file, the path of the xml config file changes from the bin directory were the app is to whatever directory the opened file is in.
So when you run the application and view the contents of the config file through the program (via a menu which displays a property grid) you see one set of values, then if you open a file and do the same thing, you see a different set of values.
Any thoughts?
dave
|
|
|
|
 |
|
 |
Solved the problem - using the full path of the config file, not just the name of the config file
dave
|
|
|
|
 |
|
 |
Of course, if you specify for the configuration file a filename like in my sample:
ConfigOpt.Initialize("MyConfig.cfg")
the file will be read/written in the "default" folder.
In the beginning, this "default" folder is the application folder, but it may change if you use - for example - an OpenFile dialog box during the application execution.
The solution is to specify a fixed configuration filename, using an absolute path. Of course, you could simply use a path like:
ConfigOpt.Initialize("C:\MyApp\MyConfig.cfg")
but you also can let .NET Framework determine your application folder at run time, as in:
ConfigOpt.Initialize(Application.StartupPath & "\MyConfig.cfg")
AV
|
|
|
|
 |
|
 |
[...]
but you also can let .NET Framework determine your application folder at run time, as in:
ConfigOpt.Initialize(Application.StartupPath & "\MyConfig.cfg")
[...]
OR EVEN:
ConfigOpt.Initialize(".\MyConfig.cfg")
Which is much easier: ".\" versus Application.StartupPath & "\"
|
|
|
|
 |
|
 |
Klaus,
sorry, but it's absolutely *WRONG* to state that "." corresponds to Application.StartupPath.
In fact (from the MS-DOS age), the directory denoted by "." is the "current OS directory", then it could be *NOT* the directory where your EXE is running. So, your solution could not work!
To prove this, follow these steps:
1) Create this simple WinApp:
Imports System.IO
Public Class Form1
[...]
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ExeName As String = Application.ExecutablePath.Substring(Application.ExecutablePath.LastIndexOf("\") + 1)
If File.Exists(Application.StartupPath & "\" & ExeName) Then
MessageBox.Show("Found: Application.StartupPath & ""\"" & ExeName")
End If
If File.Exists(".\" & ExeName) Then
MessageBox.Show("Found: "".\"" & ExeName")
End If
End Sub
End Class
2) Compile it and run it from Visual Studio - everything is OK
3) Open a Commad Prompt; move (with "CD" commands) to the "bin" directory containing the EXE you just created, and run it - everything is OK
4) Now execute a "CD .." command, to move to the parent directory (just up one level respect "bin"), and run again your EXE, by specifying, at the prompt:
C:\...> BIN\exename.EXE
This time you will see only the first MessageBox, because now your "current Windows directory" is *NOT* the same of your executable!
|
|
|
|
 |
|
 |
I see, but I'm not a lover of the ".\bin" path, so I ALWAYS generate the exe in the directory ".".
Any time I refer to a ".\icons" or ".\whatever" folder, the application succeeds in finding the right path.
Maybe this is because I don't even think to launch the application from a different dir.
I'm an "experimentor": I like to see if an idea of mine works, when it does, another one to go!
I often seek for the easiset way to solve things, and sometimes I miss some hit.
Thank you for the correction, I'll keep it in mind for the future.
|
|
|
|
 |
|
 |
Is it possible adding Isolated Storage feature by IsolatedStorageFilePermission to your class?
|
|
|
|
 |