By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,846 Members | 1,191 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,846 IT Pros & Developers. It's quick & easy.

Creatign new setting in userSettings section of app.config file

P: n/a
..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
Share this Question
Share on Google+
8 Replies


P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
>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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.