#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    73
    Rep Power
    7

    XML Web Request in BackgroundWorker


    Hello Everyone,

    So, I have a project I am working on and I cannot seem to get the background worker to perform a web request for XML, and then load a particular attributes value into my listBox1.

    It works if i just stick it in a buttons click event, but that hangs the GUI while the web request is being made so that's why I want to put it in a background worker. Any help is greatly appreciated!

    So the background worker is backgroundWorker2 and it runs the loadCmdb() function which is suppose to make the remote call + load in the host_name values to my listBox1 but nothing is occurring :( Is there a way for me to debug the call and return to see if its happening or trying to happen?

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading.Tasks;
    using System.Net;
    using Renci.SshNet;
    using System.Xml;
    using System.Text.RegularExpressions;
    namespace Command_and_Conquer
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                writeToConsole("Welcome to NeuKe Beta 0.1\n");
                this.ActiveControl = textBox4;
                this.KeyPreview = true;
                this.KeyDown += new KeyEventHandler(Form1_KeyDown);
            }
            void Form1_KeyDown(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Enter)
                {
                    NeuKeIt();
                }
            }
            
            private void writeToConsole(string msg)
            {
                DateTime now = DateTime.UtcNow;
                string currentConsole = richTextBox1.Text;
                string newConsole = currentConsole + "\n[" + now + "] [NeuKe]$ " + msg;
                richTextBox1.Text = newConsole;
                richTextBox1.SelectionStart = richTextBox1.Text.Length;
                richTextBox1.ScrollToCaret();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                backgroundWorker1.RunWorkerAsync();
            }
            private void NeuKeIt()
            {
                if (richTextBox1.Text == "help")
                {
                    writeToConsole("Help\nThis is a manual on how to use NeuKe.");
                    return;
                }
                else if (listBox1.SelectedItems.Count < 1)
                {
                    writeToConsole("You must select atleast one server.");
                    return;
                }
                else if (textBox1.Text == "" && textBox2.Text == "")
                {
                    writeToConsole("A username and password is required");
                    return;
                }
                else 
                {
                    switch (textBox4.Text)
                    {
                        case "exit":
                            Application.Exit();
                            break;
                        case "clear":
                            richTextBox1.Text = "";
                            textBox4.Focus();
                            textBox4.Text = "";
                            break;
                        case "":
                            writeToConsole("You must enter a command!");
                            textBox4.Focus();
                            break;
                        
                        default:
                        int serverCount = listBox1.SelectedItems.Count;
                        writeToConsole("Preparing "+serverCount+" missile(s)...");
                        int currentCount = 0;
                        string currentPercent = null;
                        foreach (Object selecteditem in listBox1.SelectedItems)
                        {
                            currentCount++;
                            label5.Text = currentCount + "/" + serverCount;
                            currentPercent = (currentCount / serverCount) * 100 + "%";
                            label4.Text = currentPercent;
                            try
                            {
                                string server = selecteditem as String;
                                writeToConsole("Launching at " + server);
                                Renci.SshNet.SshClient sshclient = new Renci.SshNet.SshClient(server, 22, textBox1.Text, textBox2.Text);
                                {
                                    sshclient.Connect();
                                    //if (Regex.IsMatch(textBox4.Text, "sudo"))
                                    //{
                                        //string command = Regex.Replace(textBox4.Text, "sudo", "");
                                        //string newPass = Regex.Replace(textBox2.Text, "!", "\\!");
                                        //string fullCom = "echo \"" + newPass + "\" | sudo -S " + command;
                                        //var cmd = sshclient.RunCommand(fullCom);
                                    //}
                                    //else
                                    //{
                                        var cmd = sshclient.RunCommand(textBox4.Text);
                                    //}
                                    string currentConsole = richTextBox1.Text;
                                    string newConsole = currentConsole + "\n============================================================================================================\n" + server + "\n" + cmd.Result + "\n============================================================================================================";
                                    richTextBox1.Text = newConsole;
                                    richTextBox1.SelectionStart = richTextBox1.Text.Length;
                                    richTextBox1.ScrollToCaret();
                                    sshclient.Disconnect();
                                }
    
                            }
                            catch (Exception ex)
                            {
                                //MessageBox.Show("Error: " + ex.Message);
                                writeToConsole(ex.Message);
                            }
                            finally
                            {
    
                            }
    
                        }
                        textBox4.Text = "";
                        textBox4.Focus();
                            break;
                    }
                }
            }
    
    
    
               
            private void button2_Click(object sender, EventArgs e)
            {
                writeToConsole("Loading CMDB into Server List...");
    
                backgroundWorker2.RunWorkerAsync();
            }
    
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                NeuKeIt();
            }
    
            private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
    
            }
    
            private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
    
            }
    
            private void Form1_Click(object sender, EventArgs e)
            {
                textBox4.Focus();
            }
    
            private void listBox1_Click(object sender, EventArgs e)
            {
                textBox4.Focus();
            }
    
            private void toolStripMenuItem1_Click(object sender, EventArgs e)
            {
    
            }
    
            private void loadCmdb()
            {
         
                string cmdbUrl = "myRemoteXMLurl";
    
    
                //xml request to cmdb
                WebRequest request2 = WebRequest.Create(cmdbUrl);
                request2.Credentials = new NetworkCredential("username", "password");
                using (WebResponse response2 = request2.GetResponse())
                using (XmlReader reader = XmlReader.Create(response2.GetResponseStream()))
                {
                    string element = "";
                    string a = null;
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            element = reader.Name;
                        }
                        else if (reader.NodeType == XmlNodeType.Text)
                        {
                            switch (element)
                            {
                                case "host_name":
                                    a = reader.Value;
                                    writeToConsole("Adding " + a);
                                    listBox1.Items.Add(a);
                                    break;
                            }
                        }
                    }
                }
    
            }
    
            private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
            {
                loadCmdb();
            }
    
            private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled) writeToConsole("Operation was canceled");
    
                else if (e.Error != null) writeToConsole(e.Error.Message);
    
                else writeToConsole(e.Result.ToString());
            }
    
            private void textBox3_KeyDown(object sender, KeyEventArgs e)
            {
           
            }
    
            private void textBox3_TextChanged(object sender, EventArgs e)
            {
    
            }
    
            private void button4_Click(object sender, EventArgs e)
            {
                listBox1.FindString(textBox3.Text);
            }
    
            private void button5_Click(object sender, EventArgs e)
            {
                if (!backgroundWorker2.IsBusy)
                    backgroundWorker2.CancelAsync();
                    writeToConsole("Cancelling CMDB load...");
            }
                
    
            }
    
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    73
    Rep Power
    7
    Anyone? :) I am fairly new with C# as I spend most of my days in javascript and php.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    73
    Rep Power
    7
    Originally Posted by kmhanz87
    Anyone? :) I am fairly new with C# as I spend most of my days in javascript and php.
    SOLVED!

    So, im new to backgroundWorkers and C# in general. The original thread contained the writeToConsole and its objects.. so the new thread process could not utilize this function or its objects from Form1.
    Last edited by kmhanz87; October 16th, 2013 at 06:12 PM.

IMN logo majestic logo threadwatch logo seochat tools logo