Beispiel #1
0
        /// <summary>
        /// Метод-исполнитель загрузки пакета обновлений
        /// </summary>
        public static void PackageLoader(object sender, DoWorkEventArgs e)
        {
            // Разбор аргументов
            string[] paths = (string[])e.Argument;

            // Инициализация полосы загрузки
            SupportedLanguages al     = Localization.CurrentLanguage;
            string             report = Localization.GetText("PackageDownload", al) + Path.GetFileName(paths[1]);

            ((BackgroundWorker)sender).ReportProgress((int)HardWorkExecutor.ProgressBarSize, report);

            // Отдельная обработка ModDB
            if (paths[0].Contains("www.moddb.com"))
            {
                string html = AboutForm.GetHTML(paths[0]);

                int left, right;
                if ((html == "") || ((left = html.IndexOf("<a href=\"")) < 0) ||
                    ((right = html.IndexOf("/?", left)) < 0))
                {
                    e.Result = -1;
                    return;
                }

                paths[0] = "https://www.moddb.com" + html.Substring(left + 9, right - left - 9);
            }

            // Настройка безопасности соединения
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)0xFC0;
            // Принудительно открывает TLS1.0, TLS1.1 и TLS1.2; блокирует SSL3

            // Запрос файла
            HttpWebRequest rq;

            try
            {
                rq = (HttpWebRequest)WebRequest.Create(paths[0]);
            }
            catch
            {
                e.Result = -1;
                return;
            }
            rq.Method    = "GET";
            rq.KeepAlive = false;
            rq.Timeout   = 10000;

            // Отправка запроса
            HttpWebResponse resp = null;

            try
            {
                resp = (HttpWebResponse)rq.GetResponse();
            }
            catch
            {
                // Любая ошибка здесь будет означать необходимость прекращения проверки
                e.Result = -2;
                return;
            }

            // Создание файла
            FileStream FS = null;

            try
            {
                FS = new FileStream(paths[1], FileMode.Create);
            }
            catch
            {
                resp.Close();
                e.Result = -3;
                return;
            }

            // Чтение ответа
            Stream SR = resp.GetResponseStream();

            int b;

            long length = 0, current = 0;

            try
            {
                if (paths[2].StartsWith("0x"))
                {
                    length = long.Parse(paths[2].Substring(2), NumberStyles.AllowHexSpecifier);
                }
                else
                {
                    length = long.Parse(paths[2]);
                }
            }
            catch { }

            while ((b = SR.ReadByte()) >= 0)
            {
                FS.WriteByte((byte)b);

                if ((length != 0) && (current++ % 0x1000 == 0))
                {
                    ((BackgroundWorker)sender).ReportProgress((int)(HardWorkExecutor.ProgressBarSize * current / length),
                                                              report); // Возврат прогресса
                }
                // Завершение работы, если получено требование от диалога
                if (((BackgroundWorker)sender).CancellationPending)
                {
                    SR.Close();
                    FS.Close();
                    resp.Close();

                    e.Result = 1;
                    e.Cancel = true;
                    return;
                }
            }

            SR.Close();
            FS.Close();
            resp.Close();

            // Завершено. Отображение сообщения
            ((BackgroundWorker)sender).ReportProgress(-1, Localization.GetText("PackageSuccess", al));
            Thread.Sleep(1000);

            e.Result = 0;
            return;
        }
        public static void Main()
        {
            // Инициализация
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Запрос языка приложения
            SupportedLanguages al = Localization.CurrentLanguage;

            // Проверка запуска единственной копии
            bool  result;
            Mutex instance = new Mutex(true, ProgramDescription.AssemblyTitle, out result);

            if (!result)
            {
                MessageBox.Show(string.Format(Localization.GetText("AlreadyStarted", al), ProgramDescription.AssemblyTitle),
                                ProgramDescription.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Проверка наличия обязательных компонентов
            if (!File.Exists(RDGenerics.AppStartupPath + ProgramDescription.AssemblyRequirements[0]))
            {
                if (MessageBox.Show(string.Format(Localization.GetText("LibraryNotFound", al),
                                                  ProgramDescription.AssemblyRequirements[0]) + Localization.GetText("LibraryNotFound_Lib0", al),
                                    ProgramDescription.AssemblyTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    AboutForm af = new AboutForm(null);
                }
                return;
            }

            if (!File.Exists(RDGenerics.AppStartupPath + ProgramDescription.AssemblyRequirements[1]))
            {
                if (MessageBox.Show(string.Format(Localization.GetText("LibraryNotFound", al),
                                                  ProgramDescription.AssemblyRequirements[1]) + Localization.GetText("LibraryNotFound_Lib1", al),
                                    ProgramDescription.AssemblyTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    AboutForm af = new AboutForm("http://www.un4seen.com");
                }
                return;
            }

            // Проверка корреткности версии библиотеки CDLib.dll (BASS проверяется позже)
            if (ConcurrentDrawLib.CDLibVersion != ProgramDescription.AssemblyLibVersion)
            {
                if (MessageBox.Show(string.Format(Localization.GetText("LibraryIsIncompatible", al),
                                                  ProgramDescription.AssemblyRequirements[0], ConcurrentDrawLib.CDLibVersion,
                                                  ProgramDescription.AssemblyLibVersion) +
                                    Localization.GetText("LibraryNotFound_Lib0", al), ProgramDescription.AssemblyTitle,
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    AboutForm af = new AboutForm(null);
                }
                return;
            }

            // Отображение справки и запроса на принятие Политики
            if (!ProgramDescription.AcceptEULA())
            {
                return;
            }
            ProgramDescription.ShowAbout(true);

            // Запуск
            Application.Run(new ConcurrentDrawForm());
        }