none
How to make a function located in form load to run again in button click function? RRS feed

  • Question

  • Hi all,

    I am currently developing an application that read from a JSON file as shown in the figure below.:

    [
      {
        "Record": 1,
        "IPaddress": "192.168.1.9",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "/home/root/data/completed",
        "destfolder": "C:\\temp",
        "filextension": ".db",
        "removedownloaded": 1,
        "removecsv": 1,
        "removedb": 1,
        "eagleIOHost": "sftp.eagle.io",
        "eagleIOUsername": "sftp.eagle.io",
        "eagleIOpassword": "nautitech259",
        "eagleIOdirectory": "/usr/share/tomcat8"
      },
      {
        "Record": 2,
        "IPaddress": "192.168.1.10",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "/home/root/data/completed",
        "destfolder": "C:\\temp",
        "filextension": ".db",
        "removedownloaded": 1,
        "removecsv": 1,
        "removedb": 1,
        "eagleIOHost": "sftp.eagle.io",
        "eagleIOUsername": "sftp.eagle.io",
        "eagleIOpassword": "nautitech250",
        "eagleIOdirectory": "/usr/share/tomcat8"
      }
    ]

    it is a dynamic application that shows entries depending on the number of record. 

    At the back-end there is a function that ping each ip address form load and then display the IP address status whether it is "in range" or "out of range" as shown in the figure below.

    The user will click on start to begin transferring data to the local server and do other tasks, all the function in this "button click" will repeat the whole process every 10 seconds through a timer loop in order to get the IP time average per 'ms' like below:

    for (Int32 i = 0; i < 10; ++i) hosts.Add(item.IPaddress);
    
    var average = hosts.AsParallel().WithDegreeOfParallelism(64).
    Select(h => new Ping().Send(h).RoundtripTime).Average();

    and, at some points some machines will exit the network field so they will become "out of range". Therefore, the label should be updated whenever the application is running. 

    The code that run when the form is loaded is below:

     Ping p = new Ping();
    PingReply r;
    string s = item.IPaddress;
    r = p.Send(s);
    if (r.Status == IPStatus.Success)
    {
    statusLabel.Text = "In Range";
    }
    else
    {
    statusLabel.Text = "Out of Range";
    }

    This is perfectly working so the user will know how many machines are in range when they first start the application.

    However, whenever I try to integrate it in "button click" function, it doesn't recognize statusLabel as it is only declared in form load. 

    Is there a way to keep the variable statusLabel visible to the other functions and included it in the timer loop inside the button click function?

    Thank you very much in advance.


    Sami Arja

    • Moved by CoolDadTx Friday, January 10, 2020 3:03 PM Winforms related
    Friday, January 10, 2020 9:36 AM

All replies

  • Hello, 

    >it doesn't recognize

    Put fake "Record: 0" with zero size into form on standard Load.



    Sincerely, Highly skilled coding monkey.

    Friday, January 10, 2020 9:43 AM
  • Hi samiarja,

    Thank you for posting here.

    You can create a method to do this and then call it in the form load event and the button click event.

    If "statusLabel" is a control that you customize by code, you can set it as a global variable so that it can be used in all methods.

    Here is a code demo.

            private Label label = new Label();
            
            private void Form1_Load(object sender, EventArgs e)
            {
                label.Text = "test";
                this.Controls.Add(label);
                Pings("");
            }
    
            private void Pings(string host) 
            {
                Ping p = new Ping();
                PingReply r;
                r = p.Send(host);
                if (r.Status == IPStatus.Success)
                {
                    label1.Text = "In Range";
                }
                else
                {
                    label1.Text = "Out of Range";
                }
            }
            private void button1_Click(object sender, EventArgs e)
            {
                Pings("");
            }

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, January 13, 2020 2:50 AM
  • Hi Timon,

    Thanks for your solution. I have few concern, below I added more details.

    Basically, my application is dynamically adding labels and textboxes etc. depending on how many items there are in the .JSON file. Below is my full form_load code. I am not able to create a global variable for statusLabel to access it in your proposed "Pings" method. 

    I basically need to application to ping each IPs to find out if it within the range and outside the range as well as when clicking the start button, that way we always know the status of the IP and depending on the condition, the status will be updated while the application is open.

    private void Form1_Load(object sender, EventArgs e)
            {
                Start_button.Font = new Font(this.Font, FontStyle.Bold);
                Stop_button.Font = new Font(this.Font, FontStyle.Bold);
                Exit_button.Font = new Font(this.Font, FontStyle.Bold);
                FetchDataToEagleIO_button.Font = new Font(this.Font, FontStyle.Bold);
    
                Start_button.Font = new Font(Font.FontFamily, 10);
                Stop_button.Font = new Font(Font.FontFamily, 10);
                Exit_button.Font = new Font(Font.FontFamily, 10);
                FetchDataToEagleIO_button.Font = new Font(Font.FontFamily, 10);
    
                if (!File.Exists(filePath))
                {
                    MessageBox.Show("Condition not met. Application will now close!");
                    //i log the user logged in
                    this.Close();
                }
                else
                {
                    if (!File.Exists(PingPath))
                    {
                        File.Create(PingPath);
                    }
                    // Write to the file using StreamWriter class    
                    m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                    m_streamWriter.Write("IP Ping Operation Starts : ");
                    m_streamWriter.WriteLine("{0} {1}",
                    DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
                    m_streamWriter.WriteLine("================================================================================== \n");
                    m_streamWriter.Flush();
                    
                    string text = File.ReadAllText(filePath);
                    var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                    
                    foreach (var item in currentList)
                    {
                        
                        //Create labels, textboxes and progress bar dynamically
                        TextBox machineNameTextBox = new TextBox();
                        machineNameTextBox.Text = item.Machinename;
                        machineNameTextBox.Width = 100;
                        machineNameTextBox.Height = 30;
                        machineNameTextBox.Top = topOffset;
                        machineNameTextBox.Left = 100;
    
                        TextBox ipAddressTextBox = new TextBox();
                        ipAddressTextBox.Text = item.IPaddress;
                        ipAddressTextBox.Width = 100;
                        ipAddressTextBox.Height = 30;
                        ipAddressTextBox.Top = topOffset;
                        ipAddressTextBox.Left = 300;
    
                        Label machinenameLabel = new Label();
                        machinenameLabel.Text = "Machine name";
                        machinenameLabel.Width = 100;
                        machinenameLabel.Height = 30;
                        machinenameLabel.Top = topOffset;
                        machinenameLabel.Left = 10;
    
                        Label IPaddressLabel = new Label();
                        IPaddressLabel.Text = "IP Address";
                        IPaddressLabel.Width = 100;
                        IPaddressLabel.Height = 30;
                        IPaddressLabel.Top = topOffset;
                        IPaddressLabel.Left = 230;
    
                        Label statusLabel = new Label();
                        statusLabel.Text = "Status";
                        statusLabel.Width = 70;
                        statusLabel.Height = 30;
                        statusLabel.Top = topOffset;
                        statusLabel.Left = 420;
    
                        ProgressBar progressbarLabel = new ProgressBar();
                        progressbarLabel.Width = 150;
                        progressbarLabel.Height = 20;
                        progressbarLabel.Top = topOffset;
                        progressbarLabel.Left = 500;
    
                        Controls.Add(machineNameTextBox);
                        Controls.Add(ipAddressTextBox);
                        Controls.Add(machinenameLabel);
                        Controls.Add(IPaddressLabel);
                        Controls.Add(statusLabel);
                        Controls.Add(progressbarLabel);
    
                        topOffset += 40;
    
                        Ping p = new Ping();
                        PingReply r;
                        string s = item.IPaddress;
                        r = p.Send(s);
    
                        if (r.Status == IPStatus.Success)
                        {
                            statusLabel.Text = "In Range";
                        }
                        else
                        {
                            statusLabel.Text = "Out of Range";
                        }
    
                        string localDirectory = item.destfolder;
                        string filextension = item.filextension;
                        string subFolder = Path.Combine(localDirectory, "CSV");
                        string subFolder_raw = Path.Combine(localDirectory, "Data");
    
                        if (!Directory.Exists(localDirectory))
                        {
                            Directory.CreateDirectory(localDirectory);
                        }
                        if (Directory.Exists(localDirectory) && item.filextension == ".db" || item.filextension == ".DB" || item.filextension == ".Db" || item.filextension == ".dB")
                        {
                            Directory.CreateDirectory(subFolder);
                            Directory.CreateDirectory(subFolder_raw);
    
                        }
                        
                    }
                    
                }
                
            }
    

    Thank you in advance.

    Sami


    Sami Arja

    Thursday, January 16, 2020 9:40 AM
  • Your question looks like implementing a visual parser for a certain file format. You might like to open a new topic to get opinions.


    • Edited by kwikc Saturday, January 18, 2020 8:16 AM
    Thursday, January 16, 2020 4:52 PM
  • Hi samiarja,

    It may be possible to check the status before creating a label.

    Then there is a button to check the status at any time.

            int x = 1;
            private void Form1_Load(object sender, EventArgs e)
            {
                string[] hosts =  File.ReadAllLines(@"D:\test\txt\test.txt");
                foreach (var item in hosts)
                {
                    TextBox ipAddressTextBox = new TextBox();
                    ipAddressTextBox.Name = item;
                    ipAddressTextBox.Text = item;
                    ipAddressTextBox.Width = 100;
                    ipAddressTextBox.Height = 30;
                    ipAddressTextBox.Left = 300;
                    ipAddressTextBox.Top = 30 * x;
    
                    Label statusLabel = new Label();
                    statusLabel.Name = item;
                    statusLabel.Width = 150;
                    statusLabel.Height = 30;
                    statusLabel.Left = 420;
                    statusLabel.Top = 30 * x;
    
                    Ping p = new Ping();
                    PingReply r;
                    r = p.Send(item);
    
                    if (r.Status == IPStatus.Success)
                    {
                        statusLabel.Text = "In Range";
                    }
                    else
                    {
                        statusLabel.Text = "Out of Range";
                    }
                    this.Controls.Add(ipAddressTextBox);
                    this.Controls.Add(statusLabel);
                    x++;
                }
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Control.ControlCollection controlCollection = this.Controls;
            
                foreach (Control item in controlCollection)
                {
                    Label label = null;
                    Control[] controls = controlCollection.Find(item.Text, false);
                    foreach (Control control in controls)
                    {
                        if (control is Label)
                        {
                            label = (Label)control;
                        }
                    }
                    if (item is TextBox)
                    {
                        Ping p = new Ping();
                        PingReply r;
                        r = p.Send(item.Text);
    
                        if (r.Status == IPStatus.Success)
                        {
                            label.Text = "In Range";
                        }
                        else
                        {
                            label.Text = "Out of Range";
                        }
                    }
                }
            }

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, January 17, 2020 7:51 AM
  • I am reading my JSON file by reading to text 'readalltext' and then deserializing it to a list as shown below:

    string text = File.ReadAllText(filePath);
    var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);

    I found it a little bit tricky to go around converting the json file to string [] and making the entire code working as expected.

    Would you advice me to modify your code to read list or maybe that's not gonna work? and if yes how can it be implemented?

    Thanks, sami


    Sami Arja

    Friday, January 17, 2020 9:20 AM
  • Hi Sami,

    Sorry to reply to you so late, I just returned from my vacation.

    This is possible, we just need to modify the code simply.

      private void Form1_Load(object sender, EventArgs e)
            {
                string text = File.ReadAllText(filePath);
                var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                foreach (var item in currentList )
                {
                    TextBox ipAddressTextBox = new TextBox();
                    ipAddressTextBox.Name = item.IPaddress;
                    ipAddressTextBox.Text = item.IPaddress;
                    ipAddressTextBox.Width = 100;
                    ipAddressTextBox.Height = 30;
                    ipAddressTextBox.Left = 300;
                    ipAddressTextBox.Top = 30 * x;
    
                    Label statusLabel = new Label();
                    statusLabel.Name = item.IPaddress;
                    statusLabel.Width = 150;
                    statusLabel.Height = 30;
                    statusLabel.Left = 420;
                    statusLabel.Top = 30 * x;
    
                    Ping p = new Ping();
                    PingReply r;
                    r = p.Send(item.IPaddress);
    
                    if (r.Status == IPStatus.Success)
                    {
                        statusLabel.Text = "In Range";
                    }
                    else
                    {
                        statusLabel.Text = "Out of Range";
                    }
                    this.Controls.Add(ipAddressTextBox);
                    this.Controls.Add(statusLabel);
                    x++;
                }
            }

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, February 7, 2020 7:46 AM
  • Hi,

    Has your problem been solved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, February 21, 2020 9:52 AM