Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. advanced settings

advanced settings

Scheduled Pinned Locked Moved C#
debugginghelpworkspace
15 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    bfis108137
    wrote on last edited by
    #1

    I want to save a collection of custom objects. It seems that I succeed but when I try to retrieve the setting after the program restarts, the data is gone. I have searched extensively for the solution but to no avail. Here is what I have. Any help would be deeply appreciated. In my settings.cs file I have added the following code.

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public List<Account> Accounts
    {
    get
    {
    return ((List<Account>)(this["Accounts"]));
    }
    set
    {
    this["Accounts"] = value;
    }
    }

    Then I have the class marked as serializable. I have the following code at window close and as you can see it does compile so it picks up on the code and the data is there after I save it using the debugger to verify.

    Properties.Settings.Default.Accounts = accounts.List;
    Properties.Settings.Default.Save();

    All should be ok when I run the following code except the data just isn't there as it has a value of null.

    if (Properties.Settings.Default.Accounts != null)
    {
    accounts.List = Properties.Settings.Default.Accounts;
    }

    S 1 Reply Last reply
    0
    • B bfis108137

      I want to save a collection of custom objects. It seems that I succeed but when I try to retrieve the setting after the program restarts, the data is gone. I have searched extensively for the solution but to no avail. Here is what I have. Any help would be deeply appreciated. In my settings.cs file I have added the following code.

      [global::System.Configuration.UserScopedSettingAttribute()]
      [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
      public List<Account> Accounts
      {
      get
      {
      return ((List<Account>)(this["Accounts"]));
      }
      set
      {
      this["Accounts"] = value;
      }
      }

      Then I have the class marked as serializable. I have the following code at window close and as you can see it does compile so it picks up on the code and the data is there after I save it using the debugger to verify.

      Properties.Settings.Default.Accounts = accounts.List;
      Properties.Settings.Default.Save();

      All should be ok when I run the following code except the data just isn't there as it has a value of null.

      if (Properties.Settings.Default.Accounts != null)
      {
      accounts.List = Properties.Settings.Default.Accounts;
      }

      S Offline
      S Offline
      SledgeHammer01
      wrote on last edited by
      #2

      Did you check the XML file to make sure its getting written out?

      B 1 Reply Last reply
      0
      • S SledgeHammer01

        Did you check the XML file to make sure its getting written out?

        B Offline
        B Offline
        bfis108137
        wrote on last edited by
        #3

        Where does it put the xml file and if it's not writing to the xml file where should I look to find out why?

        S 1 Reply Last reply
        0
        • B bfis108137

          Where does it put the xml file and if it's not writing to the xml file where should I look to find out why?

          S Offline
          S Offline
          SledgeHammer01
          wrote on last edited by
          #4

          On Windows 7 it'll put it in C:\Users\\AppData\\\\user.config Your code looks like it should work, just make sure you call Properties.Settings.Default.Save(); and write the value to Properties.Settings.Default.PropName. How are you specifying versions? If you are doing the auto increment version thing (or you change your version number between runs), there is an additional step you need to do to migrate the settings. You will need to call UpgradeSettings(). However, that is only needed when the version number changes. If you are using auto increment version numbers, your version will change everytime you compile, so you'd need to call UpgradeSettings() all the time. If you are just leaving it at 1.0.0.0 or whatever for now, UpgradeSettings() is not the issue, just keep in mind you'll need to use it in the real, final implementation.

          B 1 Reply Last reply
          0
          • S SledgeHammer01

            On Windows 7 it'll put it in C:\Users\\AppData\\\\user.config Your code looks like it should work, just make sure you call Properties.Settings.Default.Save(); and write the value to Properties.Settings.Default.PropName. How are you specifying versions? If you are doing the auto increment version thing (or you change your version number between runs), there is an additional step you need to do to migrate the settings. You will need to call UpgradeSettings(). However, that is only needed when the version number changes. If you are using auto increment version numbers, your version will change everytime you compile, so you'd need to call UpgradeSettings() all the time. If you are just leaving it at 1.0.0.0 or whatever for now, UpgradeSettings() is not the issue, just keep in mind you'll need to use it in the real, final implementation.

            B Offline
            B Offline
            bfis108137
            wrote on last edited by
            #5

            At the moment I don't have versions so upgrade isn't the issue. As you can see by the code, it is being saved and as I noted before, the class is there because I can see it right there in the debugger. I assume that because I can see it in the debugger that there is no serialization issue but maybe I am wrong. The class itself is not too complex. It is 4 strings and 2 decimal variables so I think it can be serialized. I checked where you said and there is no xml file so that is definitely the issue. I just don't know why there is no xml file.

            S 1 Reply Last reply
            0
            • B bfis108137

              At the moment I don't have versions so upgrade isn't the issue. As you can see by the code, it is being saved and as I noted before, the class is there because I can see it right there in the debugger. I assume that because I can see it in the debugger that there is no serialization issue but maybe I am wrong. The class itself is not too complex. It is 4 strings and 2 decimal variables so I think it can be serialized. I checked where you said and there is no xml file so that is definitely the issue. I just don't know why there is no xml file.

              S Offline
              S Offline
              SledgeHammer01
              wrote on last edited by
              #6

              What does your AssemblyInfo.cs look like? Are you getting any exceptions? Are you running the app as admin or some kind of restricted user? What does your app.config look like? EDIT: I looked back at your original post and it seems like you hand edited the settings.cs file? So the issue might be that your app.config is out of sync (doesn't contain the necessary entries).

              B 1 Reply Last reply
              0
              • S SledgeHammer01

                What does your AssemblyInfo.cs look like? Are you getting any exceptions? Are you running the app as admin or some kind of restricted user? What does your app.config look like? EDIT: I looked back at your original post and it seems like you hand edited the settings.cs file? So the issue might be that your app.config is out of sync (doesn't contain the necessary entries).

                B Offline
                B Offline
                bfis108137
                wrote on last edited by
                #7

                I did not edit the app.config file at all. What do I need to put in the app.config file?

                S 1 Reply Last reply
                0
                • B bfis108137

                  I did not edit the app.config file at all. What do I need to put in the app.config file?

                  S Offline
                  S Offline
                  SledgeHammer01
                  wrote on last edited by
                  #8

                  Yeah, that's what drives the whole thing :). Did you create the Settings.settings file? You should create your settings through the Visual Studio settings editor and that'll populate the app.config for you.

                  B 1 Reply Last reply
                  0
                  • S SledgeHammer01

                    Yeah, that's what drives the whole thing :). Did you create the Settings.settings file? You should create your settings through the Visual Studio settings editor and that'll populate the app.config for you.

                    B Offline
                    B Offline
                    bfis108137
                    wrote on last edited by
                    #9

                    I would have done that from the beginning but my type is not supported there.

                    S 1 Reply Last reply
                    0
                    • B bfis108137

                      I would have done that from the beginning but my type is not supported there.

                      S Offline
                      S Offline
                      SledgeHammer01
                      wrote on last edited by
                      #10

                      You can do custom types there, but its a little tricky :). Once you get your code all compiling, in the type you select Browse and in the edit box, you type in the fully qualified name of your type. Hmm... I just tried this in VS2012 and I guess they don't write to the app.config for custom types anymore. They did in 2010. Did you check your AssemblyInfo.cs file? If you don't have a company name specified, it won't work. That I did just verify. In addition, what does your Account class look like? Do you have public PROPERTIES and not public variables? Do you have a public parameterless constructor? I didn't need the constructor in my test app that i just tried... just trying to trouble shoot all the gotchas :).

                      B 2 Replies Last reply
                      0
                      • S SledgeHammer01

                        You can do custom types there, but its a little tricky :). Once you get your code all compiling, in the type you select Browse and in the edit box, you type in the fully qualified name of your type. Hmm... I just tried this in VS2012 and I guess they don't write to the app.config for custom types anymore. They did in 2010. Did you check your AssemblyInfo.cs file? If you don't have a company name specified, it won't work. That I did just verify. In addition, what does your Account class look like? Do you have public PROPERTIES and not public variables? Do you have a public parameterless constructor? I didn't need the constructor in my test app that i just tried... just trying to trouble shoot all the gotchas :).

                        B Offline
                        B Offline
                        bfis108137
                        wrote on last edited by
                        #11

                        I didn't have a company but I added it and it didn't help. I will just put the code for the class and the nested class. Also as I noted before I never touched the app.config file so if I do need to make changes to that then I would need to know how to do that. Here is the Accounts class

                        [Serializable]
                        public class Accounts
                        {
                        public Accounts()
                        {
                        List = new List();
                        }

                            public List List { get; set; }
                            
                            
                            public decimal TotalBalance()
                            {
                                decimal balance = 0;
                                foreach (Account a in List)
                                {
                                    balance += a.Balance;
                                }
                                return balance;
                            }
                        
                            public decimal TotalEquity()
                            {
                                decimal equity = 0;
                                foreach (Account a in List)
                                {
                                    equity += a.Equity;
                                }
                                return equity;
                            }
                        }
                        

                        And here is the Account class

                        [Serializable]
                        public class Account
                        {
                        public Account(string path)
                        {
                        Path = path;
                        Initialize();
                        }

                            private bool Initialize()
                            {
                                using (FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
                                {
                                    using (StreamReader reader = new StreamReader(fs))
                                    {
                                        while (!reader.EndOfStream)
                                        {
                                            var line = reader.ReadLine();
                                            var values = line.Split(',');
                                            Broker = values\[0\];
                                            Name = values\[1\];
                                            AccountNumber = values\[2\];
                                            Balance = decimal.Parse(values\[3\]);
                                            Equity = decimal.Parse(values\[4\]);
                                            break;
                                        }
                                    }
                                }
                                return true;
                            }
                        
                            public bool Update()
                            {
                                using (FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
                                {
                                    using (StreamReader reader = new StreamReader(fs))
                                    {
                                        while (!reader.EndOfStream)
                                        {
                                            var line = reader.ReadLine();
                                            var values = line.Split(',');
                                            Balance = decimal.Parse(values\[3\]);
                                            Equity = decimal.Parse(values\[4\]);
                        
                        A 1 Reply Last reply
                        0
                        • S SledgeHammer01

                          You can do custom types there, but its a little tricky :). Once you get your code all compiling, in the type you select Browse and in the edit box, you type in the fully qualified name of your type. Hmm... I just tried this in VS2012 and I guess they don't write to the app.config for custom types anymore. They did in 2010. Did you check your AssemblyInfo.cs file? If you don't have a company name specified, it won't work. That I did just verify. In addition, what does your Account class look like? Do you have public PROPERTIES and not public variables? Do you have a public parameterless constructor? I didn't need the constructor in my test app that i just tried... just trying to trouble shoot all the gotchas :).

                          B Offline
                          B Offline
                          bfis108137
                          wrote on last edited by
                          #12

                          ok so after getting frustrated I decided to run a test. My thinking was that maybe it can't save it. It would seem this is correct but I don't know why. I tried to save a string using the same method and it worked without editing the app.config file. So then I would try just to save one instance of the nested class Account and it did not work either so who knows.

                          1 Reply Last reply
                          0
                          • B bfis108137

                            I didn't have a company but I added it and it didn't help. I will just put the code for the class and the nested class. Also as I noted before I never touched the app.config file so if I do need to make changes to that then I would need to know how to do that. Here is the Accounts class

                            [Serializable]
                            public class Accounts
                            {
                            public Accounts()
                            {
                            List = new List();
                            }

                                public List List { get; set; }
                                
                                
                                public decimal TotalBalance()
                                {
                                    decimal balance = 0;
                                    foreach (Account a in List)
                                    {
                                        balance += a.Balance;
                                    }
                                    return balance;
                                }
                            
                                public decimal TotalEquity()
                                {
                                    decimal equity = 0;
                                    foreach (Account a in List)
                                    {
                                        equity += a.Equity;
                                    }
                                    return equity;
                                }
                            }
                            

                            And here is the Account class

                            [Serializable]
                            public class Account
                            {
                            public Account(string path)
                            {
                            Path = path;
                            Initialize();
                            }

                                private bool Initialize()
                                {
                                    using (FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
                                    {
                                        using (StreamReader reader = new StreamReader(fs))
                                        {
                                            while (!reader.EndOfStream)
                                            {
                                                var line = reader.ReadLine();
                                                var values = line.Split(',');
                                                Broker = values\[0\];
                                                Name = values\[1\];
                                                AccountNumber = values\[2\];
                                                Balance = decimal.Parse(values\[3\]);
                                                Equity = decimal.Parse(values\[4\]);
                                                break;
                                            }
                                        }
                                    }
                                    return true;
                                }
                            
                                public bool Update()
                                {
                                    using (FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
                                    {
                                        using (StreamReader reader = new StreamReader(fs))
                                        {
                                            while (!reader.EndOfStream)
                                            {
                                                var line = reader.ReadLine();
                                                var values = line.Split(',');
                                                Balance = decimal.Parse(values\[3\]);
                                                Equity = decimal.Parse(values\[4\]);
                            
                            A Offline
                            A Offline
                            Alan N
                            wrote on last edited by
                            #13

                            A class will not xml serialize unless it has a public parameterless constructor. For successful deserialization it must be possible to completely set the object's state by assigning values to it's public properties. In effect the deserializer is doing something like this:

                            Account acc = new Account();
                            acc.Broker = savedBroker;
                            acc.Name = savedName;
                            .... etc.

                            Without the necessary public parameterless constructor the serialization will silently fail (really helpful Microsoft!). You can add the constructor but then it looks like an Account cannot be restored fully as the object is strongly coupled to a specific file via the Update method and the Path has not been serialized. Think about the design carefully before adding a public Path property as the information stored in the file and in the serialized settings may be different. Alan.

                            B 1 Reply Last reply
                            0
                            • A Alan N

                              A class will not xml serialize unless it has a public parameterless constructor. For successful deserialization it must be possible to completely set the object's state by assigning values to it's public properties. In effect the deserializer is doing something like this:

                              Account acc = new Account();
                              acc.Broker = savedBroker;
                              acc.Name = savedName;
                              .... etc.

                              Without the necessary public parameterless constructor the serialization will silently fail (really helpful Microsoft!). You can add the constructor but then it looks like an Account cannot be restored fully as the object is strongly coupled to a specific file via the Update method and the Path has not been serialized. Think about the design carefully before adding a public Path property as the information stored in the file and in the serialized settings may be different. Alan.

                              B Offline
                              B Offline
                              bfis108137
                              wrote on last edited by
                              #14

                              Is this only for certain kinds of serialization because I just in the past few minutes successfully manually persisted the objects using the following code. It works perfectly except that it uses a file that the user can screw with which I wanted to avoid. I.E. They could move the program without the file. for loading

                              if (File.Exists(settingsFileName))
                              {
                              Stream TestFileStream = File.OpenRead(settingsFileName);
                              BinaryFormatter deserializer = new BinaryFormatter();
                              accounts = (Accounts)deserializer.Deserialize(TestFileStream);
                              TestFileStream.Close();
                              foreach (Account a in accounts.List)
                              {
                              ListViewItem item = new ListViewItem(new string[] { a.Broker, a.Name, a.AccountNumber, a.Balance.ToString(), a.Equity.ToString() });
                              listView1.Items.Add(item);
                              }
                              }

                              for saving

                                      Stream TestFileStream = File.Create(settingsFileName);
                                      BinaryFormatter serializer = new BinaryFormatter();
                                      serializer.Serialize(TestFileStream, accounts);
                                      TestFileStream.Close();
                              
                              A 1 Reply Last reply
                              0
                              • B bfis108137

                                Is this only for certain kinds of serialization because I just in the past few minutes successfully manually persisted the objects using the following code. It works perfectly except that it uses a file that the user can screw with which I wanted to avoid. I.E. They could move the program without the file. for loading

                                if (File.Exists(settingsFileName))
                                {
                                Stream TestFileStream = File.OpenRead(settingsFileName);
                                BinaryFormatter deserializer = new BinaryFormatter();
                                accounts = (Accounts)deserializer.Deserialize(TestFileStream);
                                TestFileStream.Close();
                                foreach (Account a in accounts.List)
                                {
                                ListViewItem item = new ListViewItem(new string[] { a.Broker, a.Name, a.AccountNumber, a.Balance.ToString(), a.Equity.ToString() });
                                listView1.Items.Add(item);
                                }
                                }

                                for saving

                                        Stream TestFileStream = File.Create(settingsFileName);
                                        BinaryFormatter serializer = new BinaryFormatter();
                                        serializer.Serialize(TestFileStream, accounts);
                                        TestFileStream.Close();
                                
                                A Offline
                                A Offline
                                Alan N
                                wrote on last edited by
                                #15

                                Yes, binary serialisation works differently and does not have the constructor/public property constraints of xml. There is information on MSDN but it's quite heavy going and the implications of what they're saying may not become apparent until you've made a few mistakes of your own. Serialization[^] Good luck, Alan.

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups