简体   繁体   中英

Unable to create a new JSON from a user input when the button is clicked, window form application C#

I am building a C# application using VS2017 windows form application. The app will take the user input and it will save it to a JSON. The problem is that the application takes only one user input, and I want to create a new JSON string with new data with the same structure and link it to a button.

The application has multiple textboxes and buttons where the user can enter information and click on the button. Save button will save the user input to a JSON file in a new string. Delete button will delete the existing string. Close button will close the whole application. Add button will a new JSON string depending on the user input.

I am mainly concern about adding a new string when the button is clicked. That way the user information will be saved and retrieved at a later stage.

This is the interface of the application. Click here

The JSON file is created by the user information and structured like below, note all user will have the same structured JSON when they click on ADD button:

{
  "Record": 1,
  "IPaddress": "168.192.6.***",
  "Machinename": "TAURUS",
  "username": "root",
  "password": "****",
  "sourcefolder": "............./............/..............",
  "destfolder": "............./............/..............",
  "filextension": "db",
  "removedownloaded": 0
}

This JSON file is created like this:

class Datalogger
        {
            public int Record
            {
                get;
                set;
            }
            public string IPaddress
            {
                get;
                set;
            }
            public string Machinename
            {
                get;
                set;
            }
            public string username
            {
                get;
                set;
            }
            public string password
            {
                get;
                set;
            }
            public string sourcefolder
            {
                get;
                set;
            }
            public string destfolder
            {
                get;
                set;
            }
            public string filextension
            {
                get;
                set;
            }
            public int removedownloaded
            {
                get;
                set;
            }

        }

and saving the user information is done like this, and it is successfully working by serializing and writing to the JSON:

private void button1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to Save", "SAVE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Datalogger myself = new Datalogger
                {
                    Record = ++count,
                    IPaddress = textBox2.Text,
                    Machinename = textBox8.Text,
                    username = textBox4.Text,
                    password = textBox3.Text,
                    sourcefolder = textBox7.Text,
                    destfolder = textBox6.Text,
                    filextension = textBox5.Text,

                };
                filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";
                // Serialize it.
                string serializedJson = JsonConvert.SerializeObject(myself);
                // Print on the screen.  
                Console.WriteLine(serializedJson);
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(myself, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(filePath, output);
            }
            else
            {
                this.Activate();
            }

        }

Now how to make the ADD button generate another JSON string with the new user input while counting the number of the string in the recording field? The example below was manually written.

[{
  "Record": 1,
  "IPaddress": "168.192.6.***",
  "Machinename": "TAURUS",
  "username": "root",
  "password": "****",
  "sourcefolder": "............./............/..............",
  "destfolder": "............./............/..............",
  "filextension": "db",
  "removedownloaded": 0
},
{
  "Record": 2,
  "IPaddress": "168.192.6.***",
  "Machinename": "TAURUS",
  "username": "tech",
  "password": "****",
  "sourcefolder": "............./............/..............",
  "destfolder": "............./............/..............",
  "filextension": "json",
  "removedownloaded": 1
},
{
  "Record": 3,
  "IPaddress": "168.192.6.***",
  "Machinename": "CAM",
  "username": "root",
  "password": "****",
  "sourcefolder": "............./............/..............",
  "destfolder": "............./............/..............",
  "filextension": "txt",
  "removedownloaded": 0
}
]

Depending on your contraints you have several solutions :

  1. Static variable If reseting the record number each time you restart your application is okay for you, you can store your index in a static int.

  2. Save on an externe support If you want persistance, you can for exemple store it in a json on a file, that you will have to read and increment each time an user click on save. That is not practical nor fast. In this case you should use a database / a local database.

So there are mutliple ways to achieve this.


First Method

This only works if your program doesn't restart in between writing the json strings to the file.

So basically you would just add a new field to your class eg private static int _rocordCounter; and change the following code:

Datalogger myself = new Datalogger
{
     Record = ++count,
     IPaddress = textBox2.Text,
     ...
};

to:

Datalogger myself = new Datalogger
{
     Record = ++_rocordCounter,
     IPaddress = textBox2.Text,
     ...
};

Second Method

In case you restart the application in between the constructions of the json strings. You can read the file you write to first and get its last entry and increment it by one.

var filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";

var product = JsonConvert.DeserializeObject<List<Product>>(File.ReadAllText(filePath ))?.LastOrDefault();
//The LastOrDefault is used to get the last element of the List.

int recordCounter = 1;
//Also we need to make sure that there is even an element.
if(product != null)
   recordCounter = product.Record + 1;

Third Method (best)

Safe your current record index in a Database, a different text file or somewhere else from disk. Then increment it every time you create a new json string and take its new value for the new record index.

In your current solution, you serialize Datalogger . Instead of you need to log Datalogger collection. eg

 public List<Datalogger> loggers {get;set;}

Then you need to handle serialize and deserialize.

string text = File.ReadAllText(file_path); 

var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text)

//Create new Datalogger

Datalogger myself = new Datalogger
                {
                    Record = 1,
                    IPaddress = textBox2.Text,
                    Machinename = textBox8.Text,
                    username = textBox4.Text,
                    password = textBox3.Text,
                    sourcefolder = textBox7.Text,
                    destfolder = textBox6.Text,
                    filextension = textBox5.Text,

                };

if(currentList != null && currentList.Any())
{
    var lastRecordNumner = currentList.OrderBy(q=>q.Record).Last().Record; 
    myself.Record = lastRecordNumner + 1;   
}
else
{
    currentList = new List<Datalogger>();
}

currentList.Add(myself);

string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);

Note: Code is not tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM