472,962 Members | 2,787 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,962 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 16043
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...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.