I am currently making a program (C# .Net 4) that has multiple options, which are saved to a file.
These options are their own variables in-code, and I was wondering if there was a way to get the variables and values of these options dynamically in code.
In my case, I have these options in a "Settings" class, and I access them from my main form class using Settings.varSetting.
I get and set these variables in multiple places in code; is it possible to consolidate the list of variables so that I can access and set them (for example, creating a Settings form which pulls the available options and their values and draws the form dynamically) more easily/consistently?
Here are the current variables I have in the Settings class:
public static Uri uriHomePage = new Uri("http://www.google.com");
public static int intInitOpacity = 100;
public static string strWindowTitle = "OpaciBrowser";
public static bool boolSaveHistory = false;
public static bool boolAutoRemoveTask = true; //Automatically remove window from task bar if under:
public static int intRemoveTaskLevel = 50; //percent
public static bool boolHideOnMinimized = true;
Thanks for any help,
Karl Tatom ( TheMusiKid )
You might want to consider using the Application Settings features built into the framework for loading and storing application settings.
var dict = typeof(Settings)
.GetFields(BindingFlags.Static | BindingFlags.Public)
.ToDictionary(f=>f.Name, f=>f.GetValue(null));
read about reflections:
http://msdn.microsoft.com/en-us/library/ms173183%28v=vs.100%29.aspx
Related
I save local user settings to xml file. Program contains "Settings" class that serialize when the program is closed and deserialize when it is started next time.
But the problem is that the program is changed all the time, and when I create next version - I want the user settings to be saved. But the program may contains new fields of settings, and then the program will started and deserialised the old xml file - new fields will be null.
Now I check every fields as hard-code in the program, as like:
Settings sts = (Settings)Deserialise(path);
if(sts.Field2 == null) sts.Field2 = "defaultvalue2";
if(sts.Field3 == null) sts.Field3 = "defaultvalue3";
Of course it is not satisfied for me. Is it possible to do "default" value of a variable as the same time when I change code of Settings class? Like this:
class Settings
{
public string Field1 (DefaultValue: "defaultvalue1");
public string Field2 (DefaultValue: "defaultvalue2");
}
public void Main
{
Settings sts = (Settings)Deserialise(path);
foreach(var fld in typeof(sts))
{
if(fld.Value == null)
fld.Value = Settings.Fields[fld].DefaulValue;
}
}
Yes it is possible, simply use the standard way to set standard values:
class Settings
{
public string Field1 = "defaultvalue1";
public string Field2 = "defaultvalue2";
}
public void Main
{
Settings sts = (Settings)Deserialise(path);
/* not needed
foreach(var fld in typeof(sts))
{
if(fld.Value == null)
fld.Value = Settings.Fields[fld].DefaulValue;
}*/
}
https://learn.microsoft.com/zh-tw/dotnet/api/system.xml.serialization.xmlattributes.xmldefaultvalue?view=netcore-3.1
here I google it . maybe try it?
Use default attribute : DefaultValueAttribute
public class Pet
{
// The default value for the Animal field is "Dog".
[DefaultValueAttribute("Dog")]
public string Animal ;
}
The Settings.settings xml file was designed for static project settings and, using user scoped settings, can be saved at runtime. Are you changing the settings so much that it no longer have the 'old' values or just adding to the list of settings?
If just adding, you don't need to loop through the settings one by one and try to guess their types with values as you can just do this:
int myInteger = Properties.Settings.Default.MyIntegerSettingValue;
And writing to the settings file:
Properties.Settings.Default.MyIntegerSettingValue = myInteger;
So if you cannot replace your settings.xml file, my suggestion is to model your settings to a class that contain all of your settings loaded at runtime and for each one missing, just write it out to the Settings file with your default value:
Properties.Settings.Default.MyMissingSetting = "MyDefaultValue"
You can find some nice info on application settings usage here
In Xamarin Android, I need to store some value in global variable which can be use through out the activities.
So how can i set and get the global variable?
I think you could use SharedPreferences.
For example, set data:
var data = GetSharedPreferences("Data", 0);
var editor = data.Edit();
editor.PutString("name","ABC");
editor.Commit();
And get data:
var data = GetSharedPreferences("Data", 0);
string name = data.GetString("name", "default");
And I think you could also try to use Application and Resource.
Create a static class and a static variables in there.
My Visual Studio extension (VSIX) is derived from the Ook Language Example (found here). Basically, I have the following ClassificationFormatDefinition with a function loadSavedColor that loads the color the user has configured. Everything works fine.
[Name("some_unique_name")]
internal sealed class OokE : ClassificationFormatDefinition
{
public OokE()
{
DisplayName = "ook!"; //human readable version of the name
ForegroundColor = loadSavedColor();
}
}
Question: After the user has configured a new color, I like to invalidate the existing instance of class OokE or change the existing instances and set ForegroundColor. But whatever I do the syntax color is not updated.
I've tried:
Get a reference to class OokE and update ForegroundColor.
Invalidate the corresponding ClassificationTypeDefinition:
[Export(typeof(ClassificationTypeDefinition))]
[Name("ook!")]
internal static ClassificationTypeDefinition ookExclamation = null;
After hours of sifting through code I could create something that works. The following method UpdateFont called with colorKeyName equal to "some_unique_name" does the trick. I hope it is useful for someone.
private void UpdateFont(string colorKeyName, Color c)
{
var guid2 = Guid.Parse("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}");
var flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES;
var store = GetService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage;
if (store.OpenCategory(ref guid2, (uint)flags) != VSConstants.S_OK) return;
store.SetItem(colorKeyName, new[]{ new ColorableItemInfo
{
bForegroundValid = 1,
crForeground = (uint)ColorTranslator.ToWin32(c)
}});
store.CloseCategory();
}
After setting the new color, you will need to clear the cache with the following code:
IVsFontAndColorCacheManager cacheManager = this.GetService(typeof(SVsFontAndColorCacheManager)) as IVsFontAndColorCacheManager;
cacheManager.ClearAllCaches();
var guid = new Guid("00000000-0000-0000-0000-000000000000");
cacheManager.RefreshCache(ref guid);
guid = new Guid("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}"); // Text editor category
I have a class and am setting a UID as a class property because it is used in many methods throughout the program and I don't want to keep having to pass in a value to it. The issue I'm getting is that when I run context.Response.Write(uid) and refresh the page, I get the same value every time.
If I move createRandomString() to context.Response.Write(createRandomString()), I get a new UID every time I reload.
I'm very new to using C# and coming from a PHP background, this is a bit odd for me. I would think that setting a class property would change every load. I'm thinking it probably has something to do with when the program is compiled, the UID is permanently set which still wouldn't make sense.
Code where property is getting set:
public class Emailer : IHttpHandler {
// Define UID
static string uid = createRandomString();
CreateRandomString Code:
public static string createRandomString() {
Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");
return GuidString;
}
Static fields are only instansiated once. That is why you always get the same result. Try this...
public class Emailer : IHttpHandler
{
// Define UID
string uid => createRandomString();
}
https://msdn.microsoft.com/en-us/library/aa645751(v=vs.71).aspx
Static class level members with an initialiser are only once the first time any memeber of the class (static or otherwise) is referenced.
The initialisation will only re-run when the assembly the class is contained in is unloaded from memory (e.g. when then executable is unloaded).
For an ASP application the assemblies are loaded and unloaded by the IIS process so you would fund that if you restarted the IIS process (for example) this would cause a new UID to be generated.
Solved it by keeping the fields static but setting the value upon load.
Fields:
// Define UID
static string uid = "";
// Define upload path for files
static string uploadPath = "";
Setting:
// Define UID
uid = createRandomString();
uploadPath = #"c:\" + uid + #"\";
I'm writing my first Windows Forms application using VS 2010 and C#. It does not use a database but I would like to save user settings like directory path and what check boxes are checked. What is the easiest way to save these preferences?
I suggest you to use the builtin application Settings to do it. Here is an article talking about it.
Sample usage:
MyProject.Properties.Settings.Default.MyProperty = "Something";
You can use the serializable attribute in conjunction with a 'settings' class. For small amount of information this is really your best bet as it is simple to implement. For example:
[Serializable]
public class MySettings
{
public const string Extension = ".testInfo";
[XmlElement]
public string GUID { get; set; }
[XmlElement]
public bool TurnedOn { get; set; }
[XmlElement]
public DateTime StartTime { get; set; }
public void Save(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(MySettings));
TextWriter textWriter = new StreamWriter(filePath);
serializer.Serialize(textWriter, this);
textWriter.Close();
}
public static MySettings Load(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(MySettings));
TextReader reader = new StreamReader(filePath);
MySettings data = (MySettings)serializer.Deserialize(reader);
reader.Close();
return data;
}
}
There you go. You can prety much cut and paste this directly into your code. Just add properties as needed, and don't forget the [XMLElement] attribute on your interesting properties.
Another benefit to this design is that you don't have to fiddle with the cumbersome Application.Settings approaches, and you can modify your files by hand if you need to.
I'd save the settings in an XML file. That way it's easy for the user to share their settings across machines etc.
You'll also be able to deserialize the XML as a class in your application, giving you easy access to the settings you require.
The easiest way would be in the app.config settings which you can set in the designer under project properties settings (make sure you set them as user setting not application settings or you wont be able to save them) you can then read and write them with C#
to read write just access properties on
Properties.Settings.Default.<your property>
there are also methods to save the properties to the users profile or to reset to defaults
Properties.Settings.Default.Reset();
Properties.Settings.Default.Save();
http://msdn.microsoft.com/en-us/library/a65txexh.aspx
What about adding a local dataset to your project (then create a setting table) and export the data finally to an xml file, its easy to use and more fixable
1- add columns (e.g.; settingName and settingValue) to your local table (DataTable1) using the designer,
then
//data set
DataSet1 ds = new DataSet1();
DataSet1.DataTable1DataTable settingsTable = (DataSet1.DataTable1DataTable)ds.Tables[0];
//add new setting
settingsTable.Rows.Add(new string[] { "setting1", "settingvalue1" });
//export to xml file
settingsTable.WriteXml("settings.xml");
//if you want to read ur settings back... read from xml
settingsTable.ReadXml("settings.xml");