Application setting doesn't work well - c#

I have a checkbox(Name:tarahi_algouritm) and a button(Name:button1) on my form(Name:frm_choose).I want to save the latest changes on my checkbox as user clicked on the button.it means user run the program and check the checkbox and then click on button and then close the program.when he/she Rerun it,checkbox should be checked.or someway he disable the checkbox and click on button and after another run,checkbox should be disabled.
for this, in application setting(table part) put a checkbox (Name:s_tarahi_algouritm)and choose USER in scope part..as I said changes are apply on checkbox and s_tarahi_algouritm is used for save the latest changes on checkbox.I wrote these codes:
private void frm_choose_Load(object sender, EventArgs e)
{
if (Properties.Settings.Default.s_tarahi_algouritm!=null)
tarahi_algouritm= Properties.Settings.Default.s_tarahi_algouritm;
}
private void button1_Click(object sender, EventArgs e)
{
Properties.Settings.Default.s_tarahi_algouritm = tarahi_algouritm;
Properties.Settings.Default.Save();
}
but When I make changes on checkbox and close the debug and Rerun it,changes are not applied.
what should I do?where is wrong?I am partly beginner so explain explicit.
thank you all

The problem is the settings files are written out in two parts: one to the application settings (which you can't save to) and the other to the user settings (which you can save to). You need to save the user settings (it gets written to your c:\users{userid}... directory).
Look at the most up-voted response to Farzin's link. It explains the issue as well.
Here's a more thorough explanation: App.config: User vs Application Scope
Here's an example.
I created a webform app and added a Settings file to it (called TestSettings.settings). I added two values:
When you run this application it creates a file in the application directory named the same as your executable with .config appended that contains (among other things) a element and a element. But this file only contains the initial values. If you change the value under the element and call Save() it will not update this file. It will create a file:
c:\Users{username}\AppData\Local{appname}{random_dir_name}{version}\user.config
My code to demonstrate this was:
Console.WriteLine(TestSettings.Default["UserValue"]);
TestSettings.Default["UserValue"] = "def";
TestSettings.Default.Save();

I tested many things like:
Properties.Settings.Default.Properties.Add(new System.Configuration.SettingsProperty("a"));
Properties.Settings.Default.Properties["a"].DefaultValue = "b";
Properties.Settings.Default.Save();
it has not error but do not save. In this link:
C# Settings.Default.Save() not saving?
Answered you must add Properties.Settings.Default.Reload(); after saving, I did that but not changed. It seems no one knows the answer.(I read many articles).
It looks like a cancer to me! I suggest you to easily save your settings to a xml file.
Below i add an easy xml saving method:
using System.Xml.Linq;
And
XElement settings;
try
{
settings = XElement.Load("settings.xml"); //beside the app .exe file
}
catch (Exception) // it is first time and you have not file yet.
{
settings = new XElement("settings");
settings.Save("settings.xml");
}
If you want to add new element:
settings.Add(new XElement("firstKey", tarahi_algouritm.Checked.ToString()));
settings.Save("settings.xml");
If you want to read or edit element:
XElement settings = XElement.Load("settings.xml");
string firstKey = settings.Element("firstKey").Value; //reading value
settings.Element("firstKey").Value = "New Value"; //Edit
settings.Save("settings.xml"); //Save
Remember that firstKey is only a name and you can use another names instead.

Related

How do I save multiple user settings in runtime in C#

I am trying to make my app stay the way I left it after closing the app. Therefore I want to save set of items from ListView to the settings and I can't figure out how to do that. I've found some solutions but I believe they are outdated as they don't seem to work.
Image shows set of items in ListView which I want to save so they appear there after restarting the app:
Items
This is where I want them to appear:
Settings
And this is part of code that I've tried out so far
private void btn_SaveConfig_Click(object sender, EventArgs e)
{
int i = 0;
Settings.Default["IP"] = tBox_discoverServerFrom.Text;
Settings.Default["DiscoveredServers"] = cBox_discoveredServers.Text;
foreach (var item in lV_groups.Items)
{
var property = new System.Configuration.SettingsProperty("Group"+i);
property.PropertyType = typeof(string);
property.Name = "Group " + i;
Settings.Default.Properties.Add(property);
Settings.Default.Save();
i++;
}
}
I do not think using the Settings API is a great idea if you want to save any significant amount of data.
I would recommend the following
Create a class describing all the data you want to save. To make serialization easier it should have a parameter less constructor and public setters for all properties. This is sometimes called a Data-Transfer-Object (DTO)
Use json to serialize the object to a file. You would normally place the file in a subfolder in the local app data folder: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).
Do the reverse when you start the application. If there is a file, use Json to deserialize it and use it however you want.
You may optionally add logic to save the file periodically, this would allow recovery in case of application crashes. You might also want some system to keep more than one file, in case the application or computer crashes in the middle of a save operation, and the file becomes corrupt.

Where are the settings stored?

NOTE: The "possible duplicate" question refers to a totally and complete different theme (refering to visual studio user settings". This question is not related to that at all. Please verify before marking "possible duplicates"
I am trying to save some settings of my program between calls and I did what this tutorial says.
It works very well. A little too well...
To summarize I created settings.settings file. Then in the form closing file, I wrote code to save the settings
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.TheSetting = settingNumber;
Properties.Settings.Default.Save();
}
and in the load function code to retrieve the setting
private void Form1_Load(object sender, EventArgs e)
{
DateTime t = DateTime.Now;
if (Properties.Settings.Default.TheDate.Date == t.Date) //it is today
{
settingNumber = Properties.Settings.Default.TheSetting;
}
else
{
//we start again
settingNumber = 0;
}
textBox1.Text = settingNumber.ToString();
}
I tried and run it several times, now the setting Number is 39.
However, and this is the strange thing this value is not found anywhere. I opened the .exe.config file that is supposed to hold the setting values and they have totally different numbers. Even if I edit them (as in the tutorial) the program still runs with its number.
Where are these setting values stored?
Thanks to user swamy I found the required file.
It was in AppData folder (which is in the corresponding User Folder) then Local, and under the a folder named after the program and the file name is user.config. The path is a really long one
I read that this path can change in other versions

Recent open files in RichTextBox [duplicate]

First of all I am a newbie in C# Programming, and I need to create a simple MRU as fast as i could.
Well the thing is I've tried looking at some online examples but however I found them to be quite a bit too confusing...
So is there anyway that anyone can create a "Recently Used" section in the toolstripmenuitem without going into those complicated codes??
E.g I will not be able to understand this stuff...
Registry key:
KEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\FileMRUList
Code:
Application.UserAppDataRegistry.DeleteSubKey("MRU", false);
RegistryKey appKey = Application.UserAppDataRegistry.CreateSubKey("MRU");
dictionary
microsoft.win32
I will only need something as simple as shown in this link below http://www.codeproject.com/KB/menus/MRUHandler.aspx
So you want to create a submenu like in the screenshot? For this, you will have to:
Store the list of recently-used files somewhere. This could be the registry, or it could just be a simple textfile, which I’ll do now to keep it simple.
Learn how to generate menu items at runtime instead of in the designer.
1. Store the MRU in a file
You will probably have already declared a private field to contain your MRU, right?
private List<string> _mru = new List<string>();
Every time someone opens a file, you add this file to the beginning of the MRU, right?
_mru.Insert(0, fullFilePath);
Now, of course when the application closes, you need to save this MRU to a file. Let’s do that in the Form’s FormClosed event. Double-click the FormClosed event in the properties and write some code which looks somewhat like this:
var appDataPath = Application.UserAppDataPath;
var myAppDataPath = Path.Combine(appDataPath, "MyApplication");
var mruFilePath = Path.Combine(myAppDataPath, "MRU.txt");
File.WriteAllLines(mruFilePath, _mru);
Now we have saved the MRU in a file. Now obviously when the application starts, we need to load it again, so do something like this in the form’s Load event:
var appDataPath = Application.UserAppDataPath;
var myAppDataPath = Path.Combine(appDataPath, "MyApplication");
var mruFilePath = Path.Combine(myAppDataPath, "MRU.txt");
if (File.Exists(mruFilePath))
_mru.AddRange(File.ReadAllLines(mruFilePath));
2. Create the menu items
Now that _mru contains the file paths that we want in our menu, we need to create a new menu item for each. I’ll be assuming here that you already have a menu item in the File menu (the item called “Most Recently Used” in your screenshot) and that it is called mnuRecentlyUsed, and that we only need to create sub-items:
foreach (var path in _mru)
{
var item = new ToolStripMenuItem(path);
item.Tag = path;
item.Click += OpenRecentFile;
mnuRecentlyUsed.DropDownItems.Add(item);
}
Now all we need is the method that actually opens a file, which I called OpenRecentFile:
void OpenRecentFile(object sender, EventArgs e)
{
var menuItem = (ToolStripMenuItem) sender;
var filepath = (string) menuItem.Tag;
// Proceed to open the file
// ...
}
Disclaimer
Please don’t use any of this code unless you understand it and you are sure that it is written to do what you intended. If it needs to do something slightly different, I’m sure you can make the necessary changes yourself.
Also, I’m sure you will have noticed that the above doesn’t update the sub-menu while the program is running. If you understand how the above code works, then I’m sure you’ll be able to figure out the rest for yourself.
http://www.codeproject.com/Tips/680088/Recent-Items-Tool-Strip-Menu-Item
This project does exactly what you want

Epicor C# Opening a Folder from a button

I want to open a folder from a record pulled up in a form in Epicor. I have created a button and so far it opens up the root folder but I want it to go to a sub-folder with the record's name as the sub folder that will be created from SQL stored procedure when a new record is created.
Here is what I have so far:
private void epiButtonC1_Click(object sender, System.EventArgs args)
{
// ** Place Event Handling Code Here **
string folder = "\\\\MasterServ\\Shared\\Customer Attachments\\";
Process.Start("IExplore.exe", folder);
}
I know something needs to be added at the end of the location to call the folder using the record but im not sure what.
When trying to get data out of a control in Epicor, generally speaking you want to go to the EpiDataView to get the value and not the control itself. There are multiple layers of abstraction going on in the form that make control handling wonky.
From your example for the comments I would do this. Code untested so hopefully I didn't make a typo.
EpiDataView edvUD104 = ((EpiDataView)(oTrans.EpiDataViews["UD104"]));
if (edvUD104.HasRow)
{
string folder = "\\\\MasterServ\\Shared\\Customer Attachments\\"
+ edvUD104.dataView[edvUD104.Row]["Key1"].ToString();
Process.Start("IExplore.exe", folder);
}
Edited for readability.

How do I create a MRU in V 2010Express C# in the simplest way?

First of all I am a newbie in C# Programming, and I need to create a simple MRU as fast as i could.
Well the thing is I've tried looking at some online examples but however I found them to be quite a bit too confusing...
So is there anyway that anyone can create a "Recently Used" section in the toolstripmenuitem without going into those complicated codes??
E.g I will not be able to understand this stuff...
Registry key:
KEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\FileMRUList
Code:
Application.UserAppDataRegistry.DeleteSubKey("MRU", false);
RegistryKey appKey = Application.UserAppDataRegistry.CreateSubKey("MRU");
dictionary
microsoft.win32
I will only need something as simple as shown in this link below http://www.codeproject.com/KB/menus/MRUHandler.aspx
So you want to create a submenu like in the screenshot? For this, you will have to:
Store the list of recently-used files somewhere. This could be the registry, or it could just be a simple textfile, which I’ll do now to keep it simple.
Learn how to generate menu items at runtime instead of in the designer.
1. Store the MRU in a file
You will probably have already declared a private field to contain your MRU, right?
private List<string> _mru = new List<string>();
Every time someone opens a file, you add this file to the beginning of the MRU, right?
_mru.Insert(0, fullFilePath);
Now, of course when the application closes, you need to save this MRU to a file. Let’s do that in the Form’s FormClosed event. Double-click the FormClosed event in the properties and write some code which looks somewhat like this:
var appDataPath = Application.UserAppDataPath;
var myAppDataPath = Path.Combine(appDataPath, "MyApplication");
var mruFilePath = Path.Combine(myAppDataPath, "MRU.txt");
File.WriteAllLines(mruFilePath, _mru);
Now we have saved the MRU in a file. Now obviously when the application starts, we need to load it again, so do something like this in the form’s Load event:
var appDataPath = Application.UserAppDataPath;
var myAppDataPath = Path.Combine(appDataPath, "MyApplication");
var mruFilePath = Path.Combine(myAppDataPath, "MRU.txt");
if (File.Exists(mruFilePath))
_mru.AddRange(File.ReadAllLines(mruFilePath));
2. Create the menu items
Now that _mru contains the file paths that we want in our menu, we need to create a new menu item for each. I’ll be assuming here that you already have a menu item in the File menu (the item called “Most Recently Used” in your screenshot) and that it is called mnuRecentlyUsed, and that we only need to create sub-items:
foreach (var path in _mru)
{
var item = new ToolStripMenuItem(path);
item.Tag = path;
item.Click += OpenRecentFile;
mnuRecentlyUsed.DropDownItems.Add(item);
}
Now all we need is the method that actually opens a file, which I called OpenRecentFile:
void OpenRecentFile(object sender, EventArgs e)
{
var menuItem = (ToolStripMenuItem) sender;
var filepath = (string) menuItem.Tag;
// Proceed to open the file
// ...
}
Disclaimer
Please don’t use any of this code unless you understand it and you are sure that it is written to do what you intended. If it needs to do something slightly different, I’m sure you can make the necessary changes yourself.
Also, I’m sure you will have noticed that the above doesn’t update the sub-menu while the program is running. If you understand how the above code works, then I’m sure you’ll be able to figure out the rest for yourself.
http://www.codeproject.com/Tips/680088/Recent-Items-Tool-Strip-Menu-Item
This project does exactly what you want

Categories