using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Security;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using UrielGuy.SyntaxHighlightingTextBox;
using System.Threading;
using System.Security.Principal;
using System.Linq;

namespace BES_API_Test
{
    public partial class Form1 : Form
    {

        string xml1 = "<?xml version=\"1.0\"?><BESClientComplianceDocument Version=\"1.0\"><Date>" + DateTime.Now + "</Date><ComplianceItem><Designator>BES Client API Tester</Designator><Expression>";
        string xml2 = "</Expression><Description>BES Client API Tester</Description><Comment>Information only</Comment><QuickEval>true</QuickEval></ComplianceItem></BESClientComplianceDocument>";
        string doc = "ClientAPITester.xml";
        string siteURL = "";
        string connectDir = "";
        string requestDir = "";
        string responseDir = "";

        string installDir = ""; 
        string complianceDir = "";
        string complianceDoc = "";
        RegistryKey regKey;

        HiResTimer hrt = new HiResTimer();

        List<double> Runs = new List<double>();
        int Iterations;
        bool LastRun = false;
        
        public Form1()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false; 

            AppDomain ad = Thread.GetDomain();
            ad.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            WindowsPrincipal user = (WindowsPrincipal)Thread.CurrentPrincipal;
            if (user.IsInRole(WindowsBuiltInRole.Administrator))
            {
                // 
            }
            else
            {
                MessageBox.Show("The BES API Tester needs to run with Administrator privilege", "Admin privilege required", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(1);                
            }

            try
            {
                // Get and set the URL needed to Open session
                // HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\BigFix\ClientComplianceAPI
                regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\BigFix\\ClientComplianceAPI");
                siteURL = (String)regKey.GetValue("SiteURL");
                connectDir = (String)regKey.GetValue("ConnectDir");
                requestDir = (String)regKey.GetValue("RequestDir");
                responseDir = (String)regKey.GetValue("ResponseDir");
                regKey.Close();

                if (siteURL == null || connectDir == null || requestDir == null || responseDir == null)
                {
                    MessageBox.Show("The registry location HKLM\\SOFTWARE\\BigFix\\ClientComplianceAPI is missing one or more of the following required keys.\n\n"
                        + "SiteURL\n" + "ConnectDir\n" + "RequestDir\n" + "ResponseDir\n\n" +
                          "They are installed as part of the normal BigFix Client installation.", "Client Compliance API installation error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
                MessageBox.Show("Cannot find registry key HKLM\\SOFTWARE\\BigFix\\ClientComplianceAPI.\nThis is installed automatically as part of the Tivoli Endpoint Manager Client installation.", "Cannot find Site URL", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                String BigFixClientKey = SearchSubKeys();

                // Retrieve BES Client installation location. 
                RegistryKey regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + BigFixClientKey);

                installDir = (String)regKey.GetValue("InstallLocation");

                if (installDir == "")
                {
                    String temp = (String)regKey.GetValue("DisplayIcon");
                    temp = temp.Substring(0, temp.LastIndexOf(@"\"));
                    installDir = temp;
                } 

                regKey.Close();
            }
            catch (Exception ex)
            {
                String msg = ex.Message;

                MessageBox.Show("Cannot locate the BigFix Client executable (BESClient.exe) automatically. \n Please specify that manually next.\n It is normally located at c:\\program files\\BigFix Enterprise\\BES Client", "Cannot find Tivoli Endpoint Manager Client through registry" );
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Title = "Please locate the BigFix Client executable (BESClient.exe)";

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    installDir = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf(@"\"));
                }

            }

            // Create the __Compliance directory
            complianceDir = installDir + @"\__BESData\actionsite\__Compliance";

            try
            {
                // Determine whether the directory exists.
                if (Directory.Exists(complianceDir) == false)
                {
                    // Try to create the directory.
                    DirectoryInfo di = Directory.CreateDirectory(complianceDir);
                }
            }
            catch (Exception ex)
            {
                String err = ex.Message;
                MessageBox.Show(ex.Message, "Creating compliance directory failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                statusLabel.Text = "Error";
                statusStrip1.Refresh();
            }

            complianceDoc = complianceDir + @"\ClientAPITester.xml";

            //Some seperators
            shtb.Seperators.Add(' ');
            shtb.Seperators.Add('\r');
            shtb.Seperators.Add('\n');
            shtb.Seperators.Add(',');
            shtb.Seperators.Add('.');
            shtb.Seperators.Add(')');
            shtb.Seperators.Add('(');
            shtb.Seperators.Add('+');
            shtb.Seperators.Add('=');
            shtb.Seperators.Add('\t');
            shtb.AddHighlightDescriptor(DescriptorRecognition.StartsWith, "/*", DescriptorType.ToCloseToken, "*/", Color.Green, null, false);
            //comments, note these could be relaced with a RegEx like: "--.*$";
            shtb.AddHighlightDescriptor(DescriptorRecognition.StartsWith, "--", DescriptorType.ToEOL, Color.Green, null, false);

            // shtb.WordWrap = false;
            shtb.ScrollBars = RichTextBoxScrollBars.Both;// & RichTextBoxScrollBars.ForcedVertical;            

            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "and", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "as", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "by", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "contain", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "contained", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "contains", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "does", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "else", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "end", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "ends", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "equal", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "equals", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "exist", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "exists", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "greater", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "if", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "is", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "it", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "item", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "items", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "less", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "mod", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "no", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "not", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "number", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "of", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "or", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "start", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "starts", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "than", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "the", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "then", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "there", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "to", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "whose", DescriptorType.Word, Color.Blue, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.WholeWord, "with", DescriptorType.Word, Color.Blue, null, true);

            //text between after a ", or untill another " is found.
            //strings
            shtb.AddHighlightDescriptor(DescriptorRecognition.StartsWith, "\"", DescriptorType.ToCloseToken, "\"", Color.OrangeRed, null, true);
            shtb.AddHighlightDescriptor(DescriptorRecognition.StartsWith, "\'", DescriptorType.ToCloseToken, "\'", Color.OrangeRed, null, true);
            //New feature ToEndOfWord
            shtb.AddHighlightDescriptor(DescriptorRecognition.StartsWith, "@", DescriptorType.ToEOW, Color.Firebrick, null, true);

            // ************************************************************************************************************
            // Have the form capture keyboard events first.
            this.KeyPreview = true;
            // Assign the event handler to the form.
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
            // Assign the event handler to the text box.
            // this.textBoxRelevance.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textboxRelevance_KeyDown);

        }

        private void EvaluateQuery()
        {
            try
            {
                // resultsRichTextBox.Clear();
                // resultsRichTextBox.Refresh();
                // statusLabel.Text = "";
                // statusStrip1.Refresh();

                // string xmldoc = xml1 + SecurityElement.Escape(relevanceTextBox.Text) + xml2;
                string xmldoc = xml1 + SecurityElement.Escape(shtb.Text) + xml2;

                StreamWriter sw = new StreamWriter(complianceDoc);
                sw.WriteLine(xmldoc);
                sw.Close();

                BESCLIENTCOMPLIANCEMODLib.Session bes_session = new BESCLIENTCOMPLIANCEMODLib.Session();
                BESCLIENTCOMPLIANCEMODLib.Progress bes_progress = new BESCLIENTCOMPLIANCEMODLib.Progress();
                BESCLIENTCOMPLIANCEMODLib.Response bes_response = new BESCLIENTCOMPLIANCEMODLib.Response();

                int ret;
                statusLabel.Text = "Running...";
                // toolStripStatusLabelEvalTime.Text = "";

                statusStrip1.Refresh();

                int SessionOpenFlag = 0;

                if (!checkBoxIdleCPUUsage.Checked)
                    SessionOpenFlag = 4;

                hrt.Start();
                ret = bes_session.Open(siteURL, doc, SessionOpenFlag);

                if (ret != 0)
                {
                    throw new SessionOpenException(ret.ToString());
                }

                int compliance_progress;
                compliance_progress = bes_progress.SessionProgress();

                // 3 is busy
                while (compliance_progress == 3)
                {
                    // MessageBox.Show(bes_progress.GetPercent.ToString());
                    compliance_progress = bes_progress.SessionProgress();
                    System.Threading.Thread.Sleep(100);
                }

                int count;
                count = bes_response.ResultCount;
                if (count < 2)
                    statusLabel.Text = "Item: " + count;
                else
                    statusLabel.Text = "Items: " + count;

                String[] results = new String[count];

                resultsRichTextBox.Clear();
                resultsRichTextBox.Refresh();

                for (int i = 0; i < count; i++)
                {
                    results[i] = bes_response.get_GetRelevanceResult(i) + "\r\n";
                }

                if (checkBoxSort.Checked)
                {
                    Array.Sort(results);
                }

                for (int i = 0; i < count; i++)
                {
                    resultsRichTextBox.AppendText(results[i]);
                }

                bes_session.Close();
                hrt.Stop();

                TimeSpan t = TimeSpan.FromMilliseconds(hrt.ElapsedMicroseconds / 1000);
                TimeSpan t2;

                if (checkBoxLoop.Checked || LastRun)
                {
                    Runs.Add(hrt.ElapsedMicroseconds/1000);
                    double[] array1 = Runs.ToArray();
                    double average1 = array1.Average();
                    t2 = TimeSpan.FromMilliseconds(average1);
                    toolStripStatusLabelEvalTime.Text = "Iteration: " + Iterations.ToString() + "  Average Time: " + t2.ToString().Remove(t2.ToString().Length - 4) + "  Last Run Evaluation Time: " + t.ToString().Remove(t.ToString().Length - 4);
                }
                else
                {
                    toolStripStatusLabelEvalTime.Text = "Evaluation time: " + t.ToString().Remove(t.ToString().Length - 4);
                }

            }
            catch (Exception ex)
            {
                String msg = ex.Message;

                String ErrorCode = "";
                String ErrorMessage = "";

                if (ex.GetType().ToString() == "BES_API_Test.SessionOpenException")
                {

                    switch (ex.Message)
                    {
                        case "-1":
                            ErrorCode = "COMPLIANCE_ERROR_NOTINSTALLED = -1";
                            ErrorMessage = "BESClient is not installed";
                            break;

                        case "-2":
                            ErrorCode = "COMPLIANCE_ERROR_NOTRUNNING = -2";
                            ErrorMessage = "BESClient is not currently executing";
                            break;

                        case "-3":
                            ErrorCode = "COMPLIANCE_ERROR_NOTRESPONDING = -3";
                            ErrorMessage = "BESClient is not responding to compliance requests";
                            break;

                        case "-4":
                            ErrorCode = "COMPLIANCE_ERROR_NOTCONFIGURED = -4";
                            ErrorMessage = "Registry is not configured with RequestDir and ResponseDir settings";
                            break;

                        case "-5":
                            ErrorCode = "COMPLIANCE_ERROR_EXISTINGREQUEST = -5";
                            ErrorMessage = "BESClient is not picking up requests";
                            break;

                        case "-6":
                            ErrorCode = "COMPLIANCE_ERROR_API_BUSY = -6";
                            ErrorMessage = "Another session is open. Only one session is allowed at a time";
                            break;

                        case "-7":
                            ErrorCode = "COMPLIANCE_ERROR_RESPONSE_MALFORMED = -7";
                            ErrorMessage = "BESClient response was not formatted properly";
                            break;

                        case "-8":
                            ErrorCode = "COMPLIANCE_ERROR_RESPONSE_CLOSED = -8";
                            ErrorMessage = "You try to access a response value but you have already closed the session";
                            break;

                        case "-9":
                            ErrorCode = "COMPLIANCE_ERROR_OLD_VERSION = -9";
                            ErrorMessage = "This error code will be returned when the API determines that a version of the client on the machine does not support the client api";
                            break;

                        case "-10":
                            ErrorCode = "COMPLIANCE_ERROR_RESPONSE_READING = -10";
                            ErrorMessage = "This error occurs when the client generates unexpected output while processing the rules";
                            break;

                        case "-11":
                            ErrorCode = "COMPLIANCE_ERROR_DOC_READING = -11";
                            ErrorMessage = "This error occurs when the API cannot parse the output produced from the client";
                            break;

                        case "-13":
                            ErrorCode = "COMPLIANCE_ERROR_DOC_SITE = -13";
                            ErrorMessage = "This error occurs when the url argument of the Session.Open call does not match any site to which the client is currently subscribed";
                            break;

                        case "-14":
                            ErrorCode = "COMPLIANCE_ERROR_DOC_MISSING = -14";
                            ErrorMessage = "This error occurs when the doc argument of the Session.Open call does not exist in the __Compliance folder of the fixlet site matching the url argument";
                            break;

                        case "-15":
                            ErrorCode = "COMPLIANCE_ERROR_PENDING_CLOSE = -15";
                            ErrorMessage = "This error occurs if you attempt to call the Session.Open method and you have not closed the previous session with a Session.Close call";
                            break;

                        case "-17":
                            ErrorCode = "COMPLIANCE_ERROR_WRITING_REQUEST = -17";
                            ErrorMessage = "This error occurs when the API is unable to write the request to the client";
                            break;

                        case "-18":
                            ErrorCode = "COMPLIANCE_ERROR_NO_RESPONSE = -18";
                            ErrorMessage = "This error occurs if the BESClient fails to respond within 10 seconds of the request";
                            break;

                        case "-19":
                            ErrorCode = "COMPLIANCE_ERROR_COMPLIANCE_IO_FAILURE = -19";
                            ErrorMessage = "This error occurs if the BESClient encounters an IO error reading or writing the compliance document or intermediate state files to the client computer’s file system";
                            break;

                        case "-20":
                            ErrorCode = "COMPLIANCE_ERROR_INDEX_TOO_LARGE = -20";
                            ErrorMessage = "You will get this error in the script Err object, when you attempt to access a response whose index is larger than the number supplied by the client";
                            break;

                        case "-21":
                            ErrorCode = "COMPLIANCE_ERROR_UNEXPECTED = -21";
                            ErrorMessage = "This error frequently occurs if a document or path cannot be found. Check file names and directory paths for the compliance document , RequestDir and ResponseDir as possible causes";
                            break;

                        case "-22":
                            ErrorCode = "COMPLIANCE_ERROR_CHANGING_CONDITIONS = -22";
                            ErrorMessage = "This error code will be returned when the client detects that fixlet relevance is changing while the rules are being processed. The session should be closed and another session started until conditions stop changing and the results become stable";
                            break;

                        case "-23":
                            ErrorCode = "COMPLIANCE_ERROR_DIR_MISSING = -23";
                            ErrorMessage = "This error code is returned when the client cannot open the compliance document because the directory in which the compliance document is located, cannot be found. The second argument to Session.Open should be a file name, not a path";
                            break;

                        case "-24":
                            ErrorCode = "COMPLIANCE_ERROR_FILE_LOCKED = -24";
                            ErrorMessage = "This error code will be returned when the client cannot open the compliance document because it is locked";
                            break;

                        case "-25":
                            ErrorCode = "COMPLIANCE_ERROR_FILE_PERMISSIONS = -25";
                            ErrorMessage = "This error code is returned when the client does not have permission to read the file";
                            break;

                        default:
                            ErrorCode = "Unknown";
                            ErrorMessage = ex.Message;
                            break;
                    }
                }

                MessageBox.Show("Code:\n" + ErrorCode + "\n\n" + "Message:\n" + ErrorMessage, "Error from BES Client API", MessageBoxButtons.OK, MessageBoxIcon.Error );
                               
                statusLabel.Text = "Error: " + ErrorCode + " -> " + ErrorMessage;
                statusStrip1.Refresh();
            }

        }

        private void ManageRun()
        {
            Iterations = 0;
            Runs = new List<double>();
            LastRun = false;

            while (checkBoxLoop.Checked || Iterations == 0)
            {
                runButton.Enabled = false;
                Thread t = new Thread(EvaluateQuery);
                t.Start();
                t.Join();
                runButton.Enabled = true;
                Iterations++;
            }
        }

        private void buttonRun_Click(object sender, EventArgs e)
        {
            Thread tm = new Thread(ManageRun);
            tm.Start();
            /*
            this.Cursor = Cursors.WaitCursor;
            runButton.Enabled = false;
            EvaluateQuery();
            this.Cursor = Cursors.Default;
            runButton.Enabled = true; */
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Control && e.KeyCode.ToString() == "Return") || (e.Control && e.KeyCode.ToString() == "E"))
            {
                // When the user presses both the 'Control' key and 'E' key,
                // or the 'Control' key and 'Return' key
                // execute the query
                e.SuppressKeyPress = true;
                Thread tm = new Thread(ManageRun);
                tm.Start();
                /*
                this.Cursor = Cursors.WaitCursor;
                runButton.Enabled = false;
                EvaluateQuery();
                this.Cursor = Cursors.Default;
                runButton.Enabled = true; */
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Version 9.2 \r\n\r\nLee Wei\r\nleewei@us.ibm.com\r\nFebruary 6th, 2016\r\nDeveloped in C# using BigFix Client API", "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Help.ShowHelp(this, "Win_Inspector_Help.chm");
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
            this.Close();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
            this.Close();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            runButton.Enabled = false;
            EvaluateQuery();
            this.Cursor = Cursors.Default;
            runButton.Enabled = true;
        }

        private void debuggingInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Site URL:\n" + siteURL +
                            "\n\nBigFix Client Installation Directory:\n" + installDir
                , "Debugging info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private String SearchSubKeys()
        {
            RegistryKey myRegKey = Registry.LocalMachine;
            myRegKey = myRegKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
            String[] subkeyNames = myRegKey.GetSubKeyNames();
            String BigFixClientKey = "BigFix Client not found";
            foreach (String s in subkeyNames)
            {
                RegistryKey UninstallKey = Registry.LocalMachine;
                UninstallKey = UninstallKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + s);
                try
                {
                    Object oValue = UninstallKey.GetValue("DisplayName");
                    if (oValue.ToString() == "BigFix Enterprise Client" || 
                        oValue.ToString().ToLower().Contains("tivoli endpoint manager client") ||
                        oValue.ToString().ToLower().Contains("bigfix client"))
                                                                                                           
                    {
                        BigFixClientKey = s;
                    }
                }
                catch (NullReferenceException)
                {
                }
            }

            return BigFixClientKey;
        }

        private void checkBoxLoop_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxLoop.Checked == false)
                LastRun = true;
        }


    }

    public class SessionOpenException : System.Exception
    {
        public SessionOpenException(string message)
            : base(message)
		{
		}

    }

}