예제 #1
0
        //создаем или добавляем в существующий файл названия и версии полученных программ, если таких в нем не содержится
        void WriteSoftList()
        {
            String dataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SoftManager\\";
            String file       = dataFolder + "SoftList.csv";

            if (!Directory.Exists(dataFolder))
            {
                Directory.CreateDirectory(dataFolder);
            }
            if (!File.Exists(file))
            {
                System.IO.FileStream fs = System.IO.File.Create(file);
                fs.Close();
            }

            string[] values = File.ReadAllText(file).Split('\t');

            foreach (TabPage page in this.tabControl.Controls)
            {
                SoftGridView softGridView = (SoftGridView)page.Controls[0];
                foreach (DataGridViewRow row in softGridView.Rows)
                {
                    string softName = row.Cells[2].Value.ToString();
                    if (!values.Contains(softName))
                    {
                        File.AppendAllText(file, softName);
                        File.AppendAllText(file, "\t");
                    }
                }
            }
        }
예제 #2
0
        private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            SoftGridView softGridView = (SoftGridView)tabControl.SelectedTab.Controls[0];
            string       strExport    = Properties.Resources.Application + ";" + Properties.Resources.Version + ";" + Properties.Resources.DateOfInstalation + ";";

            strExport += Environment.NewLine.ToString();
            foreach (DataGridViewRow row in softGridView.Rows)
            {
                strExport += row.Cells[2].Value + ";" + row.Cells[3].Value + ";" + row.Cells[4].Value + ";"
                             + Environment.NewLine.ToString();
            }
            System.IO.TextWriter tw = new System.IO.StreamWriter((saveFileDialog.FileName), false, Encoding.Default);
            tw.Write(strExport);
            tw.Close();
        }
예제 #3
0
        // Точка запуска удаления программ
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            try
            {
                string       computer      = selectedTab.Text;
                SoftGridView softGreedView = ((SoftGridView)selectedTab.Controls[computer]);
                int          count         = 0;
                ArrayList    arSoftList    = new ArrayList();
                double       percentOfTask = 0;
                foreach (DataGridViewRow row in softGreedView.Rows)
                {
                    //создаем ArrayList содержащий список программ подлежащий удалению
                    if ((Boolean)row.Cells[0].Value == true)
                    {
                        string[] array = new string[4];
                        array[0] = row.Cells[1].Value.ToString();
                        array[1] = row.Cells[2].Value.ToString();
                        array[2] = row.Cells[3].Value.ToString();
                        arSoftList.Add(array);
                    }
                }
                //для подсчета шкалы прогресса
                int programCount = arSoftList.Count;
                //удаление
                foreach (string[] array in arSoftList)
                {
                    string identifyingNumber = array[0];
                    string programName       = array[1];
                    string programVersion    = array[2];
                    count++;
                    percentOfTask = ((double)count / programCount) * 100;
                    int returnMessage = WMIProcess.deleteProgram(computer, identifyingNumber,
                                                                 programName, programVersion, admin, password);
                    array[3] = returnMessage.ToString();
                    worker.ReportProgress((int)percentOfTask, array);
                }
            }
            catch (InvalidOperationException iex)
            {
                MessageBox.Show(iex.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// Нажатие кнопки сканирования, запускает процессы получения списка установленного ПО на выбранных компьютерах, после завершения сканирования отобразит окно
        /// FormSoftList со списком установленных программ для каждого компьютера на отдельной вкладке
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScan_Click(object sender, EventArgs e)
        {
            string[] computers = getSelectedComputers();

            //doneEvents нужно для того чтобы программа определила что задача сканирования для каждого из компьютеров завершена
            ManualResetEvent[] doneEvents = new ManualResetEvent[computers.Length];

            int       i          = 0;
            ArrayList dataViewes = new ArrayList();

            ThreadPool.SetMaxThreads(5, 5);
            foreach (string computer in computers)
            {
                SoftGridView softGridView = new SoftGridView();
                softGridView.Name = computer;
                dataViewes.Add(softGridView);
                ComputerEntry entry = new ComputerEntry(computer);
                bindingSource.Add(entry);
                doneEvent     = new ManualResetEvent(false);
                doneEvents[i] = doneEvent;
                WMIProcess process = new WMIProcess(entry, softGridView, doneEvent);
                process.ProgramName   = tbSoftName.Text;
                process.OptionRestart = optionRestart;
                process.RemoteMachine = computer;
                process.UserName      = tbAdmin.Text;
                process.Password      = tbPassword.Text;
                ThreadPool.QueueUserWorkItem(new WaitCallback(process.getSoftList));
                i++;
            }

            string        formName         = Properties.Resources.GettingListOfInstalledPrograms;
            string        firstColumnName  = Properties.Resources.ComputerName;
            string        secondColumnName = Properties.Resources.ProcessStatus;;
            ProgressTable progressTable    = new ProgressTable(bindingSource, this, formName, firstColumnName, secondColumnName, doneEvents);

            progressTable.ShowDialog();

            //создаем форму со списком установленного ПО, передаем в него имя пользователя и пароль, для возможности удаления программ с правами укаазанного пользователя
            //(если он указан) в новом окне
            FormSoftList softList = new FormSoftList(dataViewes, tbAdmin.Text, tbPassword.Text);

            softList.Visible = true;
        }
예제 #5
0
        /// <summary>
        /// метод для удаления строк из таблицы
        /// </summary>
        private void deleteRow()
        {
            BindingSource bindingSource = new BindingSource();
            SoftGridView  softGridView  = (SoftGridView)tabControl.SelectedTab.Controls[0];

            //из ArrayList со списком результатов удаления
            foreach (string[] array in resultList)
            {
                int           error = Convert.ToInt32(array[3]);
                string        uninstallException = new Win32Exception(error).Message;
                ComputerEntry entry = new ComputerEntry(array[1], uninstallException);
                bindingSource.Add(entry);
                int rowIndex;
                //если в процессе удаления не произошло ошибки
                if (error == 0)
                {
                    string searchString = array[0];
                    //ищем программу в таблице и удаляем
                    foreach (DataGridViewRow row in softGridView.Rows)
                    {
                        if (row.Cells[1].Value.ToString().Equals(searchString))
                        {
                            rowIndex = row.Index;
                            softGridView.Rows.RemoveAt(rowIndex);
                            break;
                        }
                    }
                }
            }
            //отображаем форму с таблицей результатов удаления
            string        formName         = Properties.Resources.RemovingResults;
            string        firstColumnName  = Properties.Resources.Application;
            string        secondColumnName = Properties.Resources.RemovingResults;
            ProgressTable progressTable    = new ProgressTable(bindingSource, this, formName, firstColumnName, secondColumnName);

            progressTable.ShowDialog();
        }
예제 #6
0
        public static ArrayList getSoftList(String computerName, String admin, String password, SoftGridView softGridView)
        {
            ArrayList softList = new ArrayList();

            try
            {
                ConnectionOptions connOptions = new ConnectionOptions();
                if (admin.Length > 0 && password.Length > 0)
                {
                    connOptions.Username = admin;
                    connOptions.Password = password;
                }
                ManagementScope managementScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2",
                                                                                    computerName), connOptions);
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Product");

                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(managementScope, query);

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    object[] row = { false, queryObj["IdentifyingNumber"].ToString(), queryObj["Name"].ToString(), queryObj["Version"].ToString(),
                                     queryObj["InstallDate"].ToString() };

                    softList.Add(row);
                }
            }
            catch (NullReferenceException e)
            {
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(softList);
        }
예제 #7
0
 public WMIProcess(ComputerEntry computerEntry, SoftGridView softGridView, ManualResetEvent doneEvent)
 {
     entry             = computerEntry;
     this.softGridView = softGridView;
     this.doneEvent    = doneEvent;
 }