473,396 Members | 1,816 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Creatign new setting in userSettings section of app.config file

..NET 2 Winforms application.
How to create new setting and set it default value in userSettings section
of app.config file or overwrite existing setting value ?

I found code below in this list which modifies Application setting section
but how to add new item to userSettings ?

Andrus.
string sPath = Path.Combine(Environment.CurrentDirectory, "myapp.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(sPath);
// If your <appSettingssection doesn't contain "test_key" you
should add it
config.AppSettings.Settings.Add("test_key", "test_value");
config.AppSettings.Settings["test_key"].Value = "test_value";
config.Save(ConfigurationSaveMode.Modified);

Jul 16 '08 #1
8 16075
Can you explain in more detail what you are trying to do? I tested the code
you provided and it appears to correctly modify the existing entry (if such
exists), or add a new one with the given value.

Best Regards,
Stanimir Stoyanov | www.stoyanoff.info

"Andrus" <ko********@hot.eewrote in message
news:uB**************@TK2MSFTNGP04.phx.gbl...
.NET 2 Winforms application.
How to create new setting and set it default value in userSettings
section of app.config file or overwrite existing setting value ?

I found code below in this list which modifies Application setting section
but how to add new item to userSettings ?

Andrus.
string sPath = Path.Combine(Environment.CurrentDirectory, "myapp.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(sPath);
// If your <appSettingssection doesn't contain "test_key" you
should add it
config.AppSettings.Settings.Add("test_key", "test_value");
config.AppSettings.Settings["test_key"].Value = "test_value";
config.Save(ConfigurationSaveMode.Modified);
Jul 16 '08 #2
I agree. "[H]ow to add new item to userSettings?" is in your post:

config.AppSettings.Settings.Add("test_key", "test_value");

You specify the "test_key" name and the "test_value" value.

"Stanimir Stoyanov" wrote:
Can you explain in more detail what you are trying to do? I tested the code
you provided and it appears to correctly modify the existing entry (if such
exists), or add a new one with the given value.

Best Regards,
Stanimir Stoyanov | www.stoyanoff.info

"Andrus" <ko********@hot.eewrote in message
news:uB**************@TK2MSFTNGP04.phx.gbl...
.NET 2 Winforms application.
How to create new setting and set it default value in userSettings
section of app.config file or overwrite existing setting value ?

I found code below in this list which modifies Application setting section
but how to add new item to userSettings ?

Andrus.
string sPath = Path.Combine(Environment.CurrentDirectory, "myapp.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(sPath);
// If your <appSettingssection doesn't contain "test_key" you
should add it
config.AppSettings.Settings.Add("test_key", "test_value");
config.AppSettings.Settings["test_key"].Value = "test_value";
config.Save(ConfigurationSaveMode.Modified);
Jul 16 '08 #3
Can you explain in more detail what you are trying to do?

Application can open 100 different MDI Forms. Every form has different name
assignet to it, like MainForm, CustomerEditForm etc.
On open each form should read its position and size from user settings. On
close it should save new settins to user-specific area in disk
(c:\Users\Jon\AppData\Local subdirectory in Vista).

When appl is installed to new computer, default values for forms positon and
size should be retrieved, different for every form name.
Best way I found is to read those from app.config file special section:

<configuration>
<configSections>
<sectionGroup name="formSettings"
type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="FormSetting"
type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</sectionGroup>
.....
</configSections>

<formSettings>
<FormSetting>
<setting name="CustomerEditForm" serializeAs="Xml">
<value>
<Location>
<X>5</X>
<Y>10</Y>
</Location>
<Size>
<Width>200</Width>
<Height>100</Height>
</Size>
</value>
</setting>
<setting name="ProductEditForm" serializeAs="Xml">
<value>
<Location>
<X>15</X>
<Y>20</Y>
</Location>
<Size>
<Width>230</Width>
<Height>80</Height>
</Size>
</value>
</setting>

....

</FormSetting>
</formSettings>
.....

In appl config time I want to add menu command "Save this form size and
position as default if user specific setting is not present".
This command should write or update userSettings/FormDefault section with
current form position and size in app.config file.
If application is used by new windows user, forms are opened in location and
size set by this command.

Every windows user can change form positon from default to other. This new
position is stored in user settins area using code below.
How to change lines

Properties.Settings.Default[ this.Name ] = formData;
Properties.Settings.Default.Save();

so that it stores setting to user settings area just like regular
userSetting ?

[DataContract]
public class FormData {
[DataMember]
public Point Location;
[DataMember]
public Size ClientSize;
}

protected override void OnFormClosing(FormClosingEventArgs e)
{
var formData = new FormData();
formData.Location = this.Location;
formData.Size = this.Size;
// How to save settings to formSettings group :
Properties.Settings.Default[ this.Name ] = formData;
Properties.Settings.Default.Save();
}

Andrus.

Jul 17 '08 #4
>I agree. "[H]ow to add new item to userSettings?" is in your post:
>
config.AppSettings.Settings.Add("test_key", "test_value");

You specify the "test_key" name and the "test_value" value.
This adds value to Application settings group.
I need to add value to User Setting scope-group so it can be stored pre-user
basis if user changes form position or size.
I tried

config.UserSettings.Settings.Add("test_key", "test_value");

but this causes compile error size no UserSettings member exists.

Andrus.
Jul 17 '08 #5
I think I see what you're trying to do, Andrus.

You might want to look into IsolatedStorage.

Here is some psudo code:

if (IsolatedStorageFileExists == false) {
CreateIsolatedStorageFile();
}
// Now your isolated storage file is guaranteed
// to exist, so you can read your values:
OpenIsolatedStorageFile();
ReadContentsFromIsolatedStorageFile();

Here is some sample code:

using System.IO.IsolatedStorage;

public Form1() {
Cursor = Cursors.WaitCursor;
Enabled = false;
try {
InitializeComponent();
m_ready = false;
m_about = new frmAbout();
m_ds = new DataSet("AIO_Test_Results");
GetCpAppData();
m_autoGenNote = new List<string>();
m_htmlHead = new List<string>();
m_ds = new DataSet();
IsolatedStorageFile store = null;
IsolatedStorageFileStream settings = null;
StreamReader reader = null;
try {
store = .IsolatedStorageFile.GetUserStoreForApplication();
settings = new IsolatedStorageFileStream("Form1.cfg", FileMode.Open,
store);
reader = new StreamReader(settings);
this.Top = ToInt32(reader.ReadLine()); // Form's Location X
this.Left = ToInt32(reader.ReadLine()); // Form's Location Y
this.Height = ToInt32(reader.ReadLine()); // Form's Height
this.Width = ToInt32(reader.ReadLine()); // Form's Width
string state = reader.ReadLine(); // Form's WindowState
if (state.Contains("Maximized") == true) {
this.WindowState = FormWindowState.Maximized;
} else if (state.Contains("Minimized") == true) {
this.WindowState = FormWindowState.Minimized;
} else {
this.WindowState = FormWindowState.Normal;
}
} catch (Exception err) { // perhaps file wasn't there
Console.WriteLine("IsolateStorage StreamReader Error: " +
err.ToString());
} finally {
if (store != null) {
if (settings != null) {
if (reader != null) {
reader.Close();
}
settings.Dispose();
}
store.Dispose();
}
}
} finally {
Enabled = true;
Cursor = Cursors.Default;
}
}

private void Form1_Closing(object sender, FormClosingEventArgs e) {
sessionTimer.Stop();
try {
IsolatedStorageFile store =
IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream settings = new
IsolatedStorageFileStream("form1.cfg", FileMode.Create, store);
StreamWriter writer = new StreamWriter(settings);
writer.WriteLine(this.Top.ToString()); // Form's Top
writer.WriteLine(this.Left.ToString()); // Form's Left
writer.WriteLine(this.Height.ToString()); // Form's Height
writer.WriteLine(this.Width.ToString()); // Form's Width
writer.WriteLine(this.WindowState.ToString()); // Form's WindowState
writer.Close();
settings.Dispose();
store.Dispose();
} catch (Exception err) {
Console.WriteLine("Form Close Error: " + err.ToString());
} // just doesn't save if there's an error
}

"Andrus" wrote:
Can you explain in more detail what you are trying to do?

Application can open 100 different MDI Forms. Every form has different name
assignet to it, like MainForm, CustomerEditForm etc.
On open each form should read its position and size from user settings. On
close it should save new settins to user-specific area in disk
(c:\Users\Jon\AppData\Local subdirectory in Vista).

When appl is installed to new computer, default values for forms positon and
size should be retrieved, different for every form name.
Best way I found is to read those from app.config file special section:

<configuration>
<configSections>
<sectionGroup name="formSettings"
type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="FormSetting"
type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</sectionGroup>
.....
</configSections>

<formSettings>
<FormSetting>
<setting name="CustomerEditForm" serializeAs="Xml">
<value>
<Location>
<X>5</X>
<Y>10</Y>
</Location>
<Size>
<Width>200</Width>
<Height>100</Height>
</Size>
</value>
</setting>
<setting name="ProductEditForm" serializeAs="Xml">
<value>
<Location>
<X>15</X>
<Y>20</Y>
</Location>
<Size>
<Width>230</Width>
<Height>80</Height>
</Size>
</value>
</setting>

....

</FormSetting>
</formSettings>
.....

In appl config time I want to add menu command "Save this form size and
position as default if user specific setting is not present".
This command should write or update userSettings/FormDefault section with
current form position and size in app.config file.
If application is used by new windows user, forms are opened in location and
size set by this command.

Every windows user can change form positon from default to other. This new
position is stored in user settins area using code below.
How to change lines

Properties.Settings.Default[ this.Name ] = formData;
Properties.Settings.Default.Save();

so that it stores setting to user settings area just like regular
userSetting ?

[DataContract]
public class FormData {
[DataMember]
public Point Location;
[DataMember]
public Size ClientSize;
}

protected override void OnFormClosing(FormClosingEventArgs e)
{
var formData = new FormData();
formData.Location = this.Location;
formData.Size = this.Size;
// How to save settings to formSettings group :
Properties.Settings.Default[ this.Name ] = formData;
Properties.Settings.Default.Save();
}

Andrus.

Jul 17 '08 #6
You might want to look into IsolatedStorage.

Your code does not retrieve default values per-window basic if they are not
present.
This is too much code for this task.
I created the following class for this. It uses default values if
user-specif settings are not present. Line

Settings.Default.Add( res );

causes compile error since there is no Add method.

How to implement Add method which at config time adds new entry to
Settings.Settings file ?

Andrus.

using System.Drawing;
using System.Runtime.Serialization;
using System.Windows.Forms;
using MyApp.Properties;
using System.Configuration;

[DataContract]
public class FormData // public is required for deserialization
{

[DataMember]
public Point Location;

[DataMember]
public Size ClientSize;

[DataMember]
public FormWindowState WindowState;

// force use Load method
FormData() { }

/// <summary>
/// Factory method to create form settings.
/// </summary>
/// <returns>Saved or default settings value</returns>
internal static FormData Load(string formName)
{
FormData res;
try
{
res = (FormData)Settings.Default[formName];
}
catch (SettingsPropertyNotFoundException)
{ // app.config file does not contain this form definition
res = new FormData();
// todo: next line causes compile error, no Add method.
// Find a way to add new setting automatically to
Settings.Settings file to avoid manual create
Settings.Default.Add( res );
}

res.FormName = formName;
return res;
}

internal void Save()
{
Settings.Default[FormName] = this;
Settings.Default.Save();
}
}

Jul 17 '08 #7
You can not add anything to "Default" because it is not a collection.

Perhaps you want "Settings.Default.Properties" instead. The Properties
collection does include an Add method.

"Andrus" wrote:
You might want to look into IsolatedStorage.

Your code does not retrieve default values per-window basic if they are not
present.
This is too much code for this task.
I created the following class for this. It uses default values if
user-specif settings are not present. Line

Settings.Default.Add( res );

causes compile error since there is no Add method.

How to implement Add method which at config time adds new entry to
Settings.Settings file ?

Andrus.

using System.Drawing;
using System.Runtime.Serialization;
using System.Windows.Forms;
using MyApp.Properties;
using System.Configuration;

[DataContract]
public class FormData // public is required for deserialization
{

[DataMember]
public Point Location;

[DataMember]
public Size ClientSize;

[DataMember]
public FormWindowState WindowState;

// force use Load method
FormData() { }

/// <summary>
/// Factory method to create form settings.
/// </summary>
/// <returns>Saved or default settings value</returns>
internal static FormData Load(string formName)
{
FormData res;
try
{
res = (FormData)Settings.Default[formName];
}
catch (SettingsPropertyNotFoundException)
{ // app.config file does not contain this form definition
res = new FormData();
// todo: next line causes compile error, no Add method.
// Find a way to add new setting automatically to
Settings.Settings file to avoid manual create
Settings.Default.Add( res );
}

res.FormName = formName;
return res;
}

internal void Save()
{
Settings.Default[FormName] = this;
Settings.Default.Save();
}
}

Jul 17 '08 #8
You can not add anything to "Default" because it is not a collection.
>
Perhaps you want "Settings.Default.Properties" instead. The Properties
collection does include an Add method.
I tried it but during retrieve I got NullReferenceException shown in
comment.
How to fix ?

Andrus.
using System.Drawing;
using System.Runtime.Serialization;
using System.Windows.Forms;
using Eetasoft.Eeva.Windows.Forms.Properties;
using System.Configuration;

/// <summary>
/// Custom type to manage serializable form settings
/// </summary>
public class FormData // public is required for deserialization
{
public Point Location;
public Size ClientSize;
public FormWindowState WindowState;
string FormName;

internal static FormData Load(string formName)
{
FormData res;
try
{
res = (FormData)Settings.Default[formName];
}
catch (SettingsPropertyNotFoundException)
{
SettingsProperty sb = new SettingsProperty(formName,
typeof(Form), new LocalFileSettingsProvider(),
false, new FormData(), SettingsSerializeAs.Xml, null,
false, false);
Settings.Default.Properties.Add(sb);

// Next line causes NullReferenceException . Why ?
//StackTrace:
// at
System.Configuration.LocalFileSettingsProvider.Get PropertyValues(SettingsContext
context, SettingsPropertyCollection properties)
// at
System.Configuration.SettingsBase.GetPropertiesFro mProvider(SettingsProvider
provider)
// at System.Configuration.SettingsBase.GetPropertyValue ByName(String
propertyName)
// at System.Configuration.SettingsBase.get_Item(String propertyName)
// at
System.Configuration.ApplicationSettingsBase.GetPr opertyValue(String
propertyName)
// at System.Configuration.ApplicationSettingsBase.get_I tem(String
propertyName)

res = (FormData)Settings.Default[formName];
}

res.FormName = formName;
return res;
}

internal void Save()
{
Settings.Default[FormName] = this;
}

}

Jul 17 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Michael | last post by:
I have a Windows Service developed in .NET. I am using a configuration file that allows me to get app settings. Now I know I have to the path for my config file like this...
8
by: Subra Mallampalli | last post by:
Hi, I am trying to use <runtime> section within the web.config file. However, the contents of the <runtime> section seem to be ignored. What am i missing here? Is <runtime> section not used by...
6
by: Mike Moore | last post by:
I'm not very familiar with the web config file. I would like to use the timeout item in the session state for our connection string, but not use the stateconnection string and sqlconnectionstring...
2
by: Ellis Yu | last post by:
Dear All, I've an application running from the network server. The config file includes some application setting and the connection string inside. If I want the application to read the config...
0
by: Thirsty Traveler | last post by:
For some reason, a config file similar to the following config file was throwing an error: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="RpcQmsTrace"...
3
by: cody | last post by:
I keep getting a null reference when trying to access my config file through my windows service, I have placed the xml config file in my debug folder with my .exe, and my code is shown below. ...
5
by: mmcd79 | last post by:
I built a VB.net application that makes use of a machine level DB connection string setting, and a user level starting location setting. The machine level setting and the default user based...
0
by: Lucky | last post by:
Hi guys, I've got a problem under reading settlings from App.config file. I've used System.Configuration to reach to the "User Settings" and "Application Settings" sections. the problem is now...
1
by: neeraj | last post by:
Hi all I have developed desktop application in c#.net. I have installed it on 15 to 20 computers which all are in network. Application having some setting in app.config file. My problem it...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.