0

Метод install_uninstall выполняется в потоке. В нем вызывается другой метод retVal_install (список ответов установки). Необходимо передать данные из retVal_install на форму для отображения хода установки в реальном времени. Подскажите как это сделать?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.DirectoryServices;
using System.Net.NetworkInformation;
using System.Management;
using System.IO;
using Path = System.IO.Path;

namespace remote_install_uninstal
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static List<string> pcname = new List<string>();
        public MainWindow()
        {
            InitializeComponent();

            Thread PC_Name = new Thread(new ThreadStart(GetPCName));
            PC_Name.Start();
        }

        public void GetPCName()
        {
            DirectoryEntry parent = new DirectoryEntry("WinNT:");
            foreach (DirectoryEntry dm in parent.Children)
            {
                DirectoryEntry coParent = new DirectoryEntry("WinNT://" + dm.Name);
                DirectoryEntries dent = coParent.Children;
                dent.SchemaFilter.Add("Computer");
                foreach (DirectoryEntry client in dent)
                {
                    pcname.Add(client.Name);
                }
            }
        }

        private void Pc_combobox_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshComboboxItems();
        }

        public void RefreshComboboxItems()
        {
            string textToSearch = pc_combobox.Text.ToUpper();

            pc_combobox.Items.Clear();

            foreach (var pc in pcname)
            {
                if (pc.Contains(textToSearch))
                {
                    pc_combobox.Items.Add(pc);
                }
            }
        }

        public void ping()
        {
            if (pc_combobox.SelectedValue == null)
                return;

            Ping PingRemotePC = new Ping();
            PingReply reply = PingRemotePC.Send(pc_combobox.SelectedValue.ToString(), 1000);
            string status = reply.Status.ToString();

            if (status == "Success")
            {
                button_install.IsEnabled = true;
            }
            else
            {
                button_install.IsEnabled = false;
                MessageBox.Show("Удаленный компьютер выключен");
            }
        }

        private void Pc_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ping();
        }

        private void Button_install_Click(object sender, RoutedEventArgs e)
        {
            Thread myThread = new Thread(new ParameterizedThreadStart(install_uninstall));
            myThread.Start(pc_combobox.Text);
            //install_uninstall(_targetIpAddress);
        }

        public void install_uninstall(object PC)
        {
            string _targetIpAddress = (string)PC;
            string[] install = { "1.msi", "2.msi", "3.msi" };
            string[] uninstall = { "1", "2", "3" };
            string retVal = "";

            ConnectionOptions options = new ConnectionOptions();
            //options.Username = @"domain\username";
            //options.Password = "password";
            ManagementScope scope = new ManagementScope(("\\\\" + _targetIpAddress + "\\root\\cimv2"), options);
            scope.Connect();

            ManagementObjectSearcher searcher;
            SelectQuery query;
            EnumerationOptions enumOptions;
            ManagementPath p = new ManagementPath("Win32_Product");
            ManagementClass classInstance = new ManagementClass(scope, p, null);
            ManagementBaseObject inParams = classInstance.GetMethodParameters("Install");
            ManagementBaseObject outParams;
            inParams["AllUsers"] = true;
            inParams["Options"] = string.Empty;

            foreach (var item in uninstall)
            {
                query = new SelectQuery("Win32_Product", "Name='" + item + "'");

                enumOptions = new EnumerationOptions();
                enumOptions.ReturnImmediately = true;
                enumOptions.Rewindable = false;

                searcher = new ManagementObjectSearcher(scope, query);

                foreach (ManagementObject app in searcher.Get())
                {
                    outParams = app.InvokeMethod("Uninstall", null, null);
                    retVal = outParams["ReturnValue"].ToString();

                    if (retVal == "0")
                    {
                        //text_install.Document.Blocks.Add(new Paragraph(new Run("The Uninstall " + item + " completed successfully.")));
                    }
                    else
                    {
                        //text_install.Document.Blocks.Add(new Paragraph(new Run("Unknown error" + outParams["ReturnValue"].ToString())));
                    }

                }
            }

            foreach (var item in install)
            {
                inParams["PackageLocation"] = @"\\" + _targetIpAddress + @"\d$\folder\" + item;
                outParams = classInstance.InvokeMethod("Install", inParams, null);
                retVal = outParams["ReturnValue"].ToString();

                retVal_install(programm, inParams, retVal, item);
            }
        }

        public void retVal_install(string[] _programm, ManagementBaseObject _inParams, string _retVal, string _item)
        {
            switch (_retVal)
            {
                case "0":

                    text_install.Document.Blocks.Add(new Paragraph(new Run("The installation " + _item + " completed successfully.")));

                    break;

                case "2":

                    text_install.Document.Blocks.Add(new Paragraph(new Run("The system cannot find the specified file. \n\r\n\r" + _inParams["PackageLocation"])));

                    break;

                case "3":

                    text_install.Document.Blocks.Add(new Paragraph(new Run("The system cannot find the path specified. \n\r\n\r" + _inParams["PackageLocation"])));

                    break;

                case "1619":

                    text_install.Document.Blocks.Add(new Paragraph(new Run("This installation package \n\r\n\r " + _inParams["PackageLocation"] + "\n\r\n\rcould not be opened, please verify that it is accessible.")));

                    break;

                case "1620":

                    text_install.Document.Blocks.Add(new Paragraph(new Run("This installation package \n\r\n\r " + _inParams["PackageLocation"] + "\n\r\n\rcould not be opened, please verify that it is a valid MSI package.")));

                    break;

                default:

                    text_install.Document.Blocks.Add(new Paragraph(new Run(_retVal)));
                    break;
            }
        }

        private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName);
            }

            DirectoryInfo[] dirs = dir.GetDirectories();
            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(destDirName, file.Name);

                if (!File.Exists(temppath))
                {
                    file.CopyTo(temppath, false);
                }
                else
                {
                    continue;
                }

            }

            // If copying subdirectories, copy them and their contents to new location.
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
    }
}
patrik
  • 55
  • Dispatcher.Invoke(...)? – tym32167 May 30 '19 at 07:34
  • @tym32167 , Спасибо. Получилось: Dispatcher.BeginInvoke(new ThreadStart(delegate { text_install.Document.Blocks.Add(new Paragraph(new Run("The installation " + _item + " completed successfully."))); })); – patrik May 30 '19 at 07:54
  • Попробуйте посмотреть в сторону MVVM паттерна, проблем с потоками не будет. – OwDafuq May 30 '19 at 10:06

0 Answers0