[.net] C# application bottleneck

Started by
5 comments, last by Chris27 15 years, 10 months ago
I've written an application for work in .net to shut down computers and start them up again using Wake On Lan. The shutdown portion uses Windows Management Instrumentation. It accesses this through the namespace System.Management. I was wondering if someone could look at my code as my program seems to slow down for about 10-15 seconds after executing the event that shutsdown the computer. It's even worse in a loop I setup that will shutdown all the comptuers at a certain time using a timer event. Here is the shutdown class that I made.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShutdownComputers
{
    class Shutdown
    {
        public void Win32Shutdown(string compName, string userName, string password, string domain)
        {
            System.Management.ConnectionOptions connection = new System.Management.ConnectionOptions();
            connection.EnablePrivileges = true;
            connection.Authority = "NTLMDomain:" + domain;
            connection.Username = userName;
            connection.Password = password;

            System.Management.ManagementScope scope =
                new System.Management.ManagementScope(@"\\" + compName + @"\root\cimv2", connection);

            scope.Options.EnablePrivileges = true;
            scope.Connect();

            System.Management.ObjectQuery query =
                new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");

            System.Management.ManagementObjectSearcher objSearcher =
                new System.Management.ManagementObjectSearcher(scope, query);

            System.Management.ManagementObjectCollection objCol = objSearcher.Get();

            foreach (System.Management.ManagementObject mo in objCol)
            {
                string[] methodArgs = { "5", "0" };     // {0}, {0} log off                                                   
                                                        // {4}, {0} forced log off
                                                        // {1}, {0} shutdown
                                                        // {5}, {0} forced shutdown
                                                        // {2}, {0} reboot
                                                        // {6}, {0} forced reboot
                                                        // {8}, {0} power off
                                                        // {C}, {0} forced power off

                mo.InvokeMethod("Win32Shutdown", methodArgs);
            }
        }
    }
} 

Here are the events that use it.
        private void btnShutdown_Click(object sender, EventArgs e)
        {
            lstStatus.Items.Clear();
            try
            {
                Shutdown shutdown = new Shutdown();
                shutdown.Win32Shutdown(lstDBComputerName.SelectedValue.ToString(), txtUsername.Text, txtPassword.Text, "public");
            }
            catch
            {
                lstStatus.Items.Add("Enter Username/Password");
            }
        }

        private void OnTick(object sender, EventArgs e)
        {
            if (// Sunday StartUp
                dsPCInfo.DateTime.Rows[0]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[0]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[0]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[0]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[0]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Monday StartUp
                || dsPCInfo.DateTime.Rows[1]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[1]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[1]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[1]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[1]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Tuesday StartUp
                || dsPCInfo.DateTime.Rows[2]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[2]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[2]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[2]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[2]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Wednesday StartUp
                || dsPCInfo.DateTime.Rows[3]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[3]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[3]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[3]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[3]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Thursday StartUp
                || dsPCInfo.DateTime.Rows[4]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[4]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[4]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[4]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[4]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                //Friday StartUp
                || dsPCInfo.DateTime.Rows[5]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[5]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[5]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[5]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[5]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Saturday StartUp
                || dsPCInfo.DateTime.Rows[6]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[6]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[6]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[6]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[6]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString())
                {
                    WakeOnLan wakeUp = new WakeOnLan();
                    lstStatus.Items.Clear();
                    for (int j = 0; j < dsPCInfo.Machines.Rows.Count; j++)
                    {
                        try
                        {
                            string strMac = dsPCInfo.Machines.Rows[j]["MACAddress"].ToString();
                            string strMac1 = strMac.Substring(0, 2);
                            string strMac2 = strMac.Substring(3, 2);
                            string strMac3 = strMac.Substring(6, 2);
                            string strMac4 = strMac.Substring(9, 2);
                            string strMac5 = strMac.Substring(12, 2);
                            string strMac6 = strMac.Substring(15, 2);

                            byte mac1 = Byte.Parse(strMac1, NumberStyles.HexNumber);
                            byte mac2 = Byte.Parse(strMac2, NumberStyles.HexNumber);
                            byte mac3 = Byte.Parse(strMac3, NumberStyles.HexNumber);
                            byte mac4 = Byte.Parse(strMac4, NumberStyles.HexNumber);
                            byte mac5 = Byte.Parse(strMac5, NumberStyles.HexNumber);
                            byte mac6 = Byte.Parse(strMac6, NumberStyles.HexNumber);

                            lstStatus.Items.Add(dsPCInfo.Machines.Rows[j]["ComputerName"].ToString()
                                + " is starting up");
                            byte[] mac = new byte[] { mac1, mac2, mac3, mac4, mac5, mac6 };
                            wakeUp.WakeUp(mac);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            if (// Sunday Shutdown
                dsPCInfo.DateTime.Rows[7]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[7]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[7]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[7]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[7]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Monday Shutdown
                || dsPCInfo.DateTime.Rows[8]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[8]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[8]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[8]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[8]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Tuesday Shutdown
                || dsPCInfo.DateTime.Rows[9]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[9]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[9]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[9]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[9]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Wednesday Shutdown
                || dsPCInfo.DateTime.Rows[10]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[10]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[10]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[10]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[10]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Thursday Shutdown
                || dsPCInfo.DateTime.Rows[11]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[11]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[11]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[11]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[11]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                //Friday Shutdown
                || dsPCInfo.DateTime.Rows[12]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[12]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[12]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[12]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[12]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString()
                // Saturday Shutdown
                || dsPCInfo.DateTime.Rows[13]["DayOfWeek"].ToString()
                == DateTime.Now.DayOfWeek.ToString()
                && dsPCInfo.DateTime.Rows[13]["Hour"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[13]["Minute"].ToString()
                + ":" + dsPCInfo.DateTime.Rows[13]["Second"].ToString()
                + " " + dsPCInfo.DateTime.Rows[13]["AMPM"].ToString()
                == DateTime.Now.ToLongTimeString())
                {
                    //ShutdownPCs shutdownPCs = new ShutdownPCs();
                    Shutdown shutdown = new Shutdown();
                    lstStatus.Items.Clear();
                    for (int j = 0; j < dsPCInfo.Machines.Rows.Count; j++)
                    {
                        try
                        {
                            /*if (PingPC.Start(dsPCInfo.Machines.Rows[j]["ComputerName"].ToString()) == true)
                            {*/
                                lstStatus.Items.Add(dsPCInfo.Machines.Rows[j]["ComputerName"].ToString()
                                    + " is shuting down");
                                //shutdownPCs.Shutdown(dsPCInfo.Machines.Rows[j]["ComputerName"].ToString(), null, null);
                                shutdown.Win32Shutdown(dsPCInfo.Machines.Rows[j]["ComputerName"].ToString(), txtUsername.Text, txtPassword.Text, "public");
                            /*}*/
                        }
                        catch
                        {
                            continue;
                        }
                    }     
                }
        }

Thanks
Advertisement
Have you tried using a profiler?
I'm some what new to programming and am not certain what a profiler is. Right now So far I've taken a basic course in VB .net, learned a decent amount about C# through reading, and am currently reading a book on C++ using the standard library. I have the basics of how most things work with regards to variables, functions, properties, and classes, but I don't know the language in depth yet. The C++ book seems to be helping me a lot in that category, but I've still got a long way to go.

Perhaps you can explain to me what a profiler is and what it does. If it's to complicated and you don't want to explain then thats OK.
Quote:Original post by Chris27
Perhaps you can explain to me what a profiler is and what it does. If it's to complicated and you don't want to explain then thats OK.


I could try, but wikipedia will likely do a much better job than I will. [smile]

Also, you have a lot of duplicate code in the third code snippet (the startup and shutdown parts). You should strive to avoid duplicate code as much as possible, as it is very error prone (you have to make sure the two snippets are identical, if you change one you have to remember to change the other, etc.)

The if check itself is also quite messy and is therefore very error-prone. You can clean it up quite a bit using loops (and perhaps additional temporary variables).

EDIT: Depending on your development environment, you may already have access to a profiler, but even if you don't, there are many free ones. Just do a google search for "C# profiler".
Thanks for you help.

I'm trying to think of what you are suggesting to me.
Are you saying instead of using or for each evaluation in the if statement I should just use the evaluation of one day and make a loop that will go through each of the index values for the different days of the week?

for(int i = 7 ; i < 13 ; i++)
{
dsPCInfo.DateTime.Rows["DayOfWeek"].ToString()
== DateTime.Now.DayOfWeek.ToString()
&& dsPCInfo.DateTime.Rows["Hour"].ToString()
+ ":" + dsPCInfo.DateTime.Rows["Minute"].ToString()
+ ":" + dsPCInfo.DateTime.Rows["Second"].ToString()
+ " " + dsPCInfo.DateTime.Rows["AMPM"].ToString()
== DateTime.Now.ToLongTimeString()
}

Other then in the if statement I don't see any duplicated code. I instantiate the shutdown class and execute the method from it to shutdown the computer once. I do the same for the Wake On Lan. The Wake On Lan doesn't seem to cause any slowdown after it executes so I'm not sure if it's because of the loop or not.
Quote:Original post by Chris27
Are you saying instead of using or for each evaluation in the if statement I should just use the evaluation of one day and make a loop that will go through each of the index values for the different days of the week?


Yep. As you can see, the code is much shorter, more readable and less error-prone!

Also, you'll need two loops, one for the startup section and one for the shutdown section. These two loops will be basically identical, except for the loop bounds. To avoid code duplication once again, you can create a function that contains the loop and accepts the lower and upper bounds for the loop as parameters. Then you just call the function twice with different loop bounds.

Also note that your loop doesn't include 13 - the condition should be: i <= 13).

BTW, the code with the strMacs could benefit from a loop as well (you'll have to use an array to do that).

EDIT: Made a correction.
Thanks for your help. I'll have to think about the mac address part. I'm already giving myself a headache thinking about how to do this with a loop and an array. :P

This topic is closed to new replies.

Advertisement