Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a message prompting the user to upgrade some equipment connected to the computer. I want to let the user disable this message in the future, by checking a box before pressing cancel.
How can I store this user option, so that next time the program executes I can avoid showing this message based on the user choice made in the last session of the application?
The two cleanest ways are the Registry and User Settings.
I prefer User Settings because:
they're in XML (no registry hacking required)
a lot of the grunt work is done by the framework
User settings persist across upgrades automatically with ClickOnce
All you need to do is go to the Setings tab in the project's properties, add a setting, and set it's type to User.
Then just save the settings after changing them:
Properties.Settings.Default.ShowDisconnectMessage = false;
Properties.Settings.Default.Save();
The registry works similarly but it requires a bit more code and is not strongly-typed:
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software",true);
Key = key.OpenSubKey("AppName", true);
key.SetValue("ShowDisconnectMessage ", "false");
You'll need to make the messages in your application use a custom form. That form will need to show the message as well as have the check box. Then you'll want to store that information somewhere. I'm going to say in the application configuration file.
So, to save the data in the configuration file, first build a few extension methods to make it easier:
public static class Extensions
{
public static void SetValue(this KeyValueConfigurationCollection o,
string key,
string val)
{
if (!o.AllKeys.Contains(key)) { o.Add(key, val); }
else { o[key].Value = val; }
}
public static string GetValue(this NameValueCollection o,
string key,
object defaultVal = null)
{
if (!o.AllKeys.Contains(key)) { return Convert.ToString(defaultVal); }
return o[key];
}
}
Then, when you want to read that value to determine if you ought to show the message, do this:
var val = (bool)ConfigurationManager.AppSettings.GetValue("ShowTheMessage");
and then when you want to save the value, do this:
var config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var app = config.AppSettings.Settings;
app.SetValue("ShowTheMessage", checkBox.Checked);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was wondering... What's the best way to save data in Unity games. JSONs? If so, how? Thanks
Here are some of the different Ways and Methods to Save data for Unity Projects:
Platform-Independent: One way of saving data in Unity3D in a Platform-independent way is to use the PlayerPrefs class. PlayerPrefs is a static class and it is very easy to use but not reliable.
PERSISTENCE - SAVING AND LOADING DATA using DontDestroyOnLoad, PlayerPrefs, and data serialization Video Tutorial by unity.
Server Side: You can also use a Server for saving data (like a combination of PHP and MySQL Database). You can use it to save Score Data, user profiles, inventory, etc., Learn More From Unity Wiki. You can also use third-party solutions like firebase etc.
For saving the in-game data to a Hard drive in a format that can be understood and loaded later on, use a .NET/Mono feature known as Serialization. Learn More
Simple JSON guide about Unity is available at Unity Wiki or officially you can see JSON serialization
SQLite (an embedded database for your app) is another great option for you to get the Free Package, it is simple and easy (and my favorite) if you know SQL.
Scriptable Object: it's a data container. Useful for unchanging data. Suitable for large unchanging data and amazingly reduce your project's memory.
The above is taken from my blog post on Data Saving Techniques for Unity3d Applications.
You can use many assets that are available for free and paid in asset store.
Save Game Free - XML and JSON saving and loading.
Syntax:
Saver.Save<T> (T data, string fileName);
Example:
Saver.Save<MyData> (myData, "myData"); // The .json extension will be added automatically
Save Game Pro - Binary saving and loading. fast and secure. Easy to use.
Syntax:
SaveGame.Save<T> (T data, string identifier);
Example:
SaveGame.Save<int> (score, "score");
If you want to store your data in server there is a simple way with PHP and MySQL. What you have to do is:
STEP 1:
Get what ever data you want from your server just in single string (code is below):
<?php
//SERVER CONNECTION
$server_name = "localhost";
$server_user = "Er.Ellison";
$server_pass = "supersecretPassword";
$server_db = "game_test_db";
$connection = new mysqli($server_name , $server_user , $server_pass , $server_db);
if(!$connection) {
die("Connection failed !" . mysqli_connect_error());
}
// QUERY
$query = "SELECT * FROM items";
$result = mysqli_query($connection , $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "id:" . $row['id'] . "|username:" . $row['username'] . "|type:" . $row['type'] . "|score:" . $row['score'] . ";";
}
}
?>
And note that you MUST SEPARATE ANY string you want with a ; or any thing that you are comfortable with that and remember that we going to use it in C# in Unity.
STEP 2:
Now you should get the data from your web like this (it will be a long string):
STEP 3:
Now go to the Unity and create a C# script and attached that to what ever object in your scene and open the script up, then use this kind of code to manipulate the data that you retrieved from your database:
public class DataLoader : MonoBehaviour {
public string[] items;
// Use this for initialization
IEnumerator Start () {
WWW itemsData = new WWW ("http://localhost/_game/test/itemsdata.php");
yield return itemsData;
string itemsDataStrign = itemsData.text;
print (itemsDataStrign);
items = itemsDataStrign.Split (';');
print (GetDataValue(items[0] , "cost:"));
}
string GetDataValue(string data, string index) {
string value = data.Substring (data.IndexOf(index) + index.Length);
if (value.Contains ("|")) {
value = value.Remove (value.IndexOf("|"));
}
return value;
}
}
STEP 4:
You just NOW retrieved data from database, check the image from unity console:
I made this for who that may be, like me, stuck in database problems!
I am developing a c# windows form application. In my application i have 3 forms (main form that has a list box and two buttons (Check in and check out), check in form and the check out form). On the main form, the list box contain user names, if a user select their name for the first time, the check in button must be enabled for the user to check in... But if the user checks in and then closes the application, when they reopen it, the button check out should be enabled and check in disabled.
I have been told to use the application/user states, but since I'm new in programming, i don't know how to implement the windows form states.
What should i do?
Thank you
There is no such thing as "Windows Forms states". You have several options to implement somthing like this, among which are:
Use a database (this makes sense if you have a varying number of users and a database server available)
Use user settings (this is a builtin mechanism of the .NET framework, but may not be suitable for lots of users)
Use a simple XML file to store the states of all users.
All three solutions require you to sort of "get into things". Write more about what you have available (database server, etc.) or whether you want a fixed number of users and I can extend this answer to help you get started.
I'm going to line out how to do number 2:
Create a little helper class that assigns a state to a user name:
public class UserState
{
public string UserName { get; set; }
public bool CheckedIn { get; set; }
public override string ToString() { return String.Format("{0}={1}", UserName, CheckedIn); }
}
This class allows you to store a user name and the checked in state and by calling ToString() get a value in the form "user=false".
Then, create a user scoped application setting (go to settings-tab of project settings and add a new setting of type System.Collections.Specialized.StringCollection) named UserStates. You can access this setting from code as Properties.Settings.Default.UserStates. It is basically a list of strings.
To add and persist a new entry you could do this:
UserState state = new UserState() { UserName = "Test", CheckedIn = false };
Properties.Settings.Default.UserStates.Add(state.ToString());
Properties.Settings.Default.Save();
The state for user "Test" (and the previously existing entries) are now stored across program restarts.
Now the idea is to build a list of users and their states when starting the program and to store this list when exiting.
Declare this as a member variable in the class:
private List<UserState> userStates = new List<UserState>();
Do the following in the form's OnLoad event:
if (Properties.Settings.Default.UserStates == null || Properties.Settings.Default.UserStates.Count == 0)
{
// Add your users to the collection initially. This is the first
// run of the application
userStates.Add(new UserState() { ... });
...
}
else
{
// Each line in the setting represents one user in the form name=state.
// We split each line into the parts and add them to the internal list.
for (int i = 0; i < Properties.Settings.Default.UserStates.Count; i++)
{
string stateLine = Properties.Settings.Default.UserStates[i];
string[] parts = stateLine.Split('=');
userStates.Add(new UserState() { UserName = parts[0].Trim(), CheckedIn = Boolean.Parse(parts[1].Trim()) });
}
}
This creates a new entry in an internal list of users for each stored line in the collection setting.
When a button is clicked, change the state in the respective UserState object in the list.
Do the following in the form's OnClose event:
// Create the collection from scratch
Properties.Settings.Default.UserStates = new System.Collections.Specialized.StringCollection();
// Add all the users and states from our internal list
foreach (UserState state in userStates)
{
Properties.Settings.Default.UserStates.Add(state.ToString());
}
// Save the settings for next start
Properties.Settings.Default.Save();
This persists the current list of user states to the setting.
Please note: I have tested this in Visual Studio now and it works. I leave the question of how to map the list box entries to the UserState objects in the internal list to you/as topic for a new question :-D
The downside of this approach: It is not very flexible - adding more states per user involves some coding.
It could be better for you to read about typed datasets and how to store/read them from XML. This gives you some sort of "database feeling" without actually having to use a database.
My speech recognition project include 2 forms form1 & form2. Form2 is my main form but before loading form2 my program take a variable value from user through form1 and pass it to form2. It means at start my program opens form1 takes value & pass it to form2 then form2 is shown.
Now my question is how to
make form1 load only at programs 1st launch after installation and after 1st launch directly form2 is loaded thereafter?
means form1 should not be loaded after that..
I suggest to use a simple textfile where you could store the input value recorded the first time your app starts, then, check if the file with the value exists and read it back.
For Example
string customValue = string.Empty;
string appData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
appData = Path.Combine(appData, "MyAppName");
if(!Directory.Exists(appData))
Directory.CreateDirectory(appData);
string appDataFile = Path.Combine(appData, "MyAppNameSettings.txt");
if(File.Exists(appDataFile))
customValue = File.ReadAllText(appDataFile);
else
{
customValue = AskUserForTheFirstTimeValue();
File.WriteAllText(appDataFile, customValue);
}
The file is stored in a subfolder of the common application data (C:\programdata) created to store your data files. You check if the file exists at first launch. If the file exists you read its content (assumed to be a simple string here), if the file doesn't exist then you ask the input and store the value for the successive runs of your app.
You can create a Registry Key in Windows Registry (regedit), and when you start your program verify if its exists and the value.
Link about Registry Keys:
http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey(v=vs.110).aspx
You should have a settings file that keeps a variable like IsFirstRun = true; This application should be distributed and compiled with this file, at start up you should read this file and if you encounter the true state you should load the appropriate forms. You should also ensure that the value is immediately set to false for the second launch condition.
have a look at .net's setting class.
There are two ways I can suggest:
First one
Use the application configuration file:
Creating such file in c# is pretty easy, per usual if you start with a standard Windows Forms Project Template you will most likely already have an app.config in that project, if not, follow instructions from here (under Application Configuration Files).
Add a simple boolean value to the file like so (that appSettings-node is created under the root configuration-node:
<appSettings>
<add key="FirstRun" value="true" />
</appSettings>
In your first form, where you do your application configuration you add code to manipulate your app.config programmatically using the ConfigurationManager-Class for the event that configuration has been finished and can be saved (probably some button click, note that you will need a Reference to System.Configuration):
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
bool myVal = bool.Parse(config.AppSettings.Settings["FirstRun"].Value);
if (myVal)
{
// MessageBox.Show("yep, its true");
config.AppSettings.Settings["FirstRun"].Value = false.ToString();
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
else
{
// MessageBox.Show("na, its not true anymore.");
}
Second one
Use a property grid for your application configuration:
Since from your description it seems you only use the first form to enter some application configuration values, I would recommend using the PropertyGrid-Control for that.
That control can be easily bound to an object that exposes some properties (what a surprise) that are then used to render a standardized control containing captions and value selection controls dependend on the property's types, for example:
public class Settings
{
public int MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
}
Then you check at your program start, whether the configuration file (you define the path) exists, and if so, try to deserialize an object from its xml (sample below works for primitive types, for more complex ones you might have to extend the serializer, but you get the idea).
That serialized object represents your saved application settings, so you do not need to open up the propertygrid-form anymore.
If no file could be found the grid gets initialized with a simple new constructed object and you show that form:
this goes into your initialization code:
FileInfo file = new FileInfo("SaveHere.xml");
if (file.Exists)
{
using(StreamReader reader = new StreamReader("SaveHere.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
Settings mySettings = (Settings)serializer.Deserialize(reader);
reader.Close();
}
}
else
{
this.propertyGrid1.SelectedObject = new Settings();
// show form code
}
this code goes into the event code where you want to save your configuration
using(StreamWriter writer = new StreamWriter("SaveHere.xml",false))
{
XmlSerializer serializer = new XmlSerializer(this.propertyGrid1.SelectedObject.GetType());
serializer.Serialize(writer, this.propertyGrid1.SelectedObject);
writer.Close();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a simple program, and I am trying to load the kongregate chat into a WebBrowser, but it is not working...
When I first start it up, it navigates to a game, and then it gives me 4 Script Error, and the chat just sits there saying: "Joining room...". I don't think it is a problem with the browser settings, because it works on internet explorer. Is there something that is messed up with my WebBrowser? I have let it sit there for a few minutes, and it still does not work. I have set the suppressScriptErrors to true and false, and it still does not fix it.
FYI: I am not doing anything bad with my program, like cheating, or spamming, or anything like that, I just want the webpage to show up, and sometimes I like to be able to have things copied, so I put a few TextBoxes to the right of it, so I can paste it into chat, if I won't to post a few things...
This article has the solution to your problem. It appears that the WebBrowser control in Visual Studio launches in IE7 mode by default. That's why you get javescript errors with the control but, not in your browser. I highly suggest you read the article linked that the top. Luckily, there is a fix. The following code was taken from another stackoverflow answer to a question that indirectly addresses your issue. Here is that link, and here is the code.
string installkey = #"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
string entryLabel = Path.GetFileName(Application.ExecutablePath);
System.OperatingSystem osInfo = System.Environment.OSVersion;
string version = osInfo.Version.Major.ToString() + '.' + osInfo.Version.Minor.ToString();
uint editFlag = (uint)((version == "6.2") ? 0x2710 : 0x2328); // 6.2 = Windows 8 and therefore IE10
RegistryKey existingSubKey = Registry.LocalMachine.OpenSubKey(installkey, false); // readonly key
if (existingSubKey == null) {
existingSubKey = Registry.LocalMachine.CreateSubKey(installkey, RegistryKeyPermissionCheck.Default); // readonly key
}
if (existingSubKey.GetValue(entryLabel) == null) {
existingSubKey = Registry.LocalMachine.OpenSubKey(installkey, true); // writable key
existingSubKey.SetValue(entryLabel, unchecked((int)editFlag), RegistryValueKind.DWord);
}
Also, the article I mentioned up top says that you should create an entry for the VS host process for your app too or it won't work in debug mode. Good luck and I hope this solves your issue!
I decided to use Properties.Settings to store some application settings for my ASP.net project. However, when trying to modify the data, I get an error The property 'Properties.Settings.Test' has no setter, since this is generated I have no idea what I should do to change this as all my previous C# Projects have not had this issues.
My guess is that you defined the property with the Application scope, rather than the User scope. Application-level properties are read-only, and can only be edited in the web.config file.
I would not use the Settings class in an ASP.NET project at all. When you write to the web.config file, ASP.NET/IIS recycles the AppDomain. If you write settings regularly, you should use some other settings store (e.g. your own XML file).
As Eli Arbel already said you can’t modify values written in web.config from your application code. You can only do this manually but then the application will restart and this is something you don’t want.
Here is a simple class you can use to store values and make them easy to read and modify. Just update the code to suite your needs if you’re reading from XML or database and depending on whether you want to permanently store modified values.
public class Config
{
public int SomeSetting
{
get
{
if (HttpContext.Current.Application["SomeSetting"] == null)
{
//this is where you set the default value
HttpContext.Current.Application["SomeSetting"] = 4;
}
return Convert.ToInt32(HttpContext.Current.Application["SomeSetting"]);
}
set
{
//If needed add code that stores this value permanently in XML file or database or some other place
HttpContext.Current.Application["SomeSetting"] = value;
}
}
public DateTime SomeOtherSetting
{
get
{
if (HttpContext.Current.Application["SomeOtherSetting"] == null)
{
//this is where you set the default value
HttpContext.Current.Application["SomeOtherSetting"] = DateTime.Now;
}
return Convert.ToDateTime(HttpContext.Current.Application["SomeOtherSetting"]);
}
set
{
//If needed add code that stores this value permanently in XML file or database or some other place
HttpContext.Current.Application["SomeOtherSetting"] = value;
}
}
}
Here:
http://msdn.microsoft.com/en-us/library/bb397755.aspx
is the solution for your problem.