示例#1
0
        private void RunUpdate()
        {
            try {
                try {
                    string file = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Program.Args[Program.PRODUCT_NAME] + ".pkg");
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                }
                catch { }

                if (!UpdatesHelper.CheckUpdates(Program.Args[Program.VERSION], Program.Args[Program.SERVER], Program.Args[Program.PRODUCT_NAME]))
                {
                    return;
                }

                InfoLabel.InvokeIfRequired(() => InfoLabel.Text = "Выполняется: Закрытие запущенной программы...");
                ProcessStartInfo Info = new ProcessStartInfo();
                Info.Arguments      = string.Format("/F /IM {0}.exe", Program.Args[Program.PRODUCT_NAME]);
                Info.WindowStyle    = ProcessWindowStyle.Hidden;
                Info.CreateNoWindow = true;
                Info.FileName       = "taskkill.exe";
                Process.Start(Info).WaitForExit();

                InfoLabel.InvokeIfRequired(() => InfoLabel.Text = "Выполняется: Загрузка обновлений...");
                string fileName = UpdatesHelper.DownloadPackage(Program.Args[Program.SERVER], Program.Args[Program.PRODUCT_NAME]);

                InfoLabel.InvokeIfRequired(() => InfoLabel.Text = "Выполняется: Установка обновлений...");
                UpdatesHelper.InstallUpdate(fileName);

                InfoLabel.InvokeIfRequired(() => InfoLabel.Text = "Готово!");
                Info           = new ProcessStartInfo();
                Info.Arguments = "-u";
                Info.FileName  = string.Format("{0}.exe", Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Program.Args[Program.PRODUCT_NAME]));
                Process.Start(Info);

                File.Delete(fileName);
            }
            catch (Exception error) {
                MessageBox.Show(error.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally {
                Application.Exit();
            }
        }
示例#2
0
        private void _ActualizareProgram_Click(object sender, RoutedEventArgs e)
        {
            string numeFisierVers = string.Empty;
            string sPath          = string.Empty;

            numeFisierVers = UpdatesHelper.Verifica_Update_Versiune(Assembly.GetExecutingAssembly().GetName().Version.ToString());
            if (numeFisierVers != "0")
            {
                if (MessageBoxResult.Yes ==
                    MessageBox.Show("Exista o versiune noua pentru descarcare\nDoriti descarcarea si instalarea noii versiuni?", "Info", MessageBoxButton.YesNo))
                {
                    sPath = Environment.CurrentDirectory + @"UpdateWEB\UpdateWEB.exe";
                    ClasaSuport.StartProgramByFileName(sPath, true);
                    Application.Current.Shutdown();
                    return;
                }
            }
            else
            {
                MessageBox.Show("Nu este necesara actualizarea programului", "Info", MessageBoxButton.OK);
            }
        }
示例#3
0
        /// <summary>
        /// Выролняет проверку наличия обновлений
        /// </summary>
        /// <returns></returns>
        public static void CheckUpdates()
        {
            if (IsUpdateRunning)
            {
                return;
            }
            IsUpdateRunning = true;

            try {
                if (ARGS.Length > 0)
                {
                    foreach (string arg in ARGS)
                    {
                        if (arg.ToLower() == "-u" && !UpdatesInstalled)
                        {
                            Process[] processes = Process.GetProcessesByName("Updater");
                            if (processes.Length > 0)
                            {
                                Process         proc = processes[0];
                                FileVersionInfo info = FileVersionInfo.GetVersionInfo(proc.MainModule.FileName);
                                if (info.CompanyName == "ФГУП Почта Крыма")
                                {
                                    proc.Kill();
                                }
                            }

                            string path = Path.Combine(CurrentDirectory, "Updater.exe");
                            if (File.Exists(path))
                            {
                                File.Delete(path);
                            }
                            File.WriteAllBytes(path, Properties.Resources.Updater);

                            // Создаем сообщение об успешной установке обновления
                            CreateMessage("Обновление успешно установлено", MessageType.Information, false, true, true);

                            UpdatesInstalled = true;
                        }
                    }
                }
            }
            catch (Exception ex) {
                CreateMessage("Ошибка при установке обновлений: " + ex.ToString(), MessageType.Error, true, false, true);
            }

            try {
                // Установка модуля обновления при его отсутствии
                string updaterPath = Path.Combine(CurrentDirectory, "Updater.exe");
                if (!File.Exists(updaterPath))
                {
                    File.WriteAllBytes(updaterPath, Properties.Resources.Updater);
                }
            }
            catch (Exception ex) {
                CreateMessage("Ошибка при распаковке клиента обновлений: " + ex.ToString(), MessageType.Error, false, false, false);
            }

            try {
                CreateMessage("Проверка обновлений конфигурационного файла...", MessageType.Information, false, false, true);
                if (UpdatesHelper.CheckConfigUpdates(Path.Combine(CurrentDirectory, "settings.upd"), Configuration))
                {
                    // Сохраняем изменения в конфигурационный файл
                    ConfHelper.SaveConfig(Configuration, Encoding.UTF8, true);
                    Configuration = ConfHelper.LoadConfig <Global>();
                    CreateMessage("Выполнено обновление конфигурационного файла", MessageType.Information, false, false, true);
                }
            }
            catch (Exception ex) {
                CreateMessage("Ошибка при установке обновлений конфигурационного файла: " + ex.ToString(), MessageType.Error, false, false, true);
            }

            try {
                CreateMessage("Проверка обновлений...", MessageType.Information, false, false, true);
                if (UpdatesHelper.CheckUpdates(Configuration.Updates.ServerName, Version, ProductName))
                {
                    Process.Start(Path.Combine(CurrentDirectory, "Updater.exe"), string.Format("{0} {1} {2}", Version, Configuration.Updates.ServerName, ProductName));
                    GUIController.ExitOnLoaded();
                    return;
                }
            }
            catch (Exception ex) {
                CreateMessage("Ошибка при проверке обновлений: " + ex.ToString(), MessageType.Error, false, false, true);
            }

            IsUpdateRunning = false;
        }
示例#4
0
        /// <summary>
        /// Инициализация движка программы
        /// </summary>
        /// <returns></returns>
        public static bool InitEngine()
        {
            try {
                if (!SecurityHelper.CheckCertificateExists(StoreName.Root, StoreLocation.CurrentUser, Configuration.Mail.CertificateName))
                {
                    CreateMessage("Сертификат почтового сервера не установлен. Необходимо выполнить установку сертификата и повторно запустить программу", MessageType.Error, true, false, true);
                    return(false);
                }

                // Инициализация параметров электронной почты
                MailHelper.Host        = Configuration.Mail.Host;
                MailHelper.Domain      = Configuration.Mail.Domain;
                MailHelper.ToRecipient = Configuration.Mail.ToRecipient;
                MailHelper.Username    = Configuration.Mail.Username;
                MailHelper.Password    = Configuration.Mail.Password;

                // Инициализация параметров ftp сервера
                FtpHelper.Host     = Configuration.Ftp.Host;
                FtpHelper.Port     = Configuration.Ftp.Port;
                FtpHelper.Cwd      = Configuration.Ftp.Cwd;
                FtpHelper.Username = Configuration.Ftp.Username;
                FtpHelper.Password = Configuration.Ftp.Password;

                // Инициализация параметров SQL
                if (!IOHelper.IsFullPath(Configuration.Sql.Database))
                {
                    Configuration.Sql.Database = Path.Combine(CurrentDirectory, Configuration.Sql.Database);
                }
                SQLHelper.ConnectionString = string.Format("User={0};Password={1};Database={2};DataSource={3};Pooling=false;Connection lifetime=60;Charset=WIN1251;",
                                                           Configuration.Sql.Username, Configuration.Sql.Password,
                                                           Configuration.Sql.Database, Configuration.Sql.DataSource);

                // Проверка временных папок на их существование
                TempPath = Path.Combine(CurrentDirectory, "Temp");
                if (!Directory.Exists(TempPath))
                {
                    Directory.CreateDirectory(TempPath);
                }
                TempTasksPath = Path.Combine(TempPath, "Tasks");
                if (!Directory.Exists(TempTasksPath))
                {
                    Directory.CreateDirectory(TempTasksPath);
                }
                TempFtpPath = Path.Combine(TempPath, "Ftp");
                if (!Directory.Exists(TempFtpPath))
                {
                    Directory.CreateDirectory(TempFtpPath);
                }
                TempSqlPath = Path.Combine(TempPath, "Sql");
                if (!Directory.Exists(TempSqlPath))
                {
                    Directory.CreateDirectory(TempSqlPath);
                }

                // Проверка задач по обработке файлов
                CreateMessage("Загрузка задач...", MessageType.Information, false, false, true);
                StringBuilder errors = new StringBuilder();
                foreach (Task task in Configuration.Tasks)
                {
                    task.Name   = task.Name.ToUpper();
                    task.Source = Environment.ExpandEnvironmentVariables(task.Source);
                    if (!string.IsNullOrWhiteSpace(task.ExternalLib))
                    {
                        task.ExternalLibAsm = Assembly.LoadFile(Path.Combine(CurrentDirectory, Environment.ExpandEnvironmentVariables(task.ExternalLib)));
                    }
                    if (!task.AllowDuplicate)
                    {
                        try {
                            SQLHelper.CreateTableFingerprint(task.Name);
                        }
                        catch (Exception ex) {
                            errors.AppendLine(string.Format("Ошибка: {0}", ex.ToString()));
                        }
                    }

                    try {
                        IOHelper.IsPathDirectory(task.Source);
                    }
                    catch (Exception ex) {
                        if (ex is FileNotFoundException || ex is DirectoryNotFoundException)
                        {
                            errors.AppendLine(string.Format("Путь '{0}' для задачи '{1}' не существует", task.Source, task.Name));
                            continue;
                        }

                        throw;
                    }
                }
                if (errors.Length > 0)
                {
                    CreateMessage("Ошибка при инициализации задач:\r\n" + errors.ToString(), MessageType.Error, false, true, true);
                }

                try {
                    // Проверка существования таблицы для хранения данных об обработанных файлах
                    SQLHelper.CreateTableOperationInfo();
                }
                catch (Exception ex) {
                    CreateMessage("Ошибка при инициализации программы:\r\n" + ex.ToString(), MessageType.Error, false, true, true);
                }

                // Настройка главного таймера
                int interval = Configuration.TaskInterval;
                MainTimer          = new Timer();
                MainTimer.Interval = Math.Max(MinimumMainTimerInterval, interval);

                // Настройка таймера обновлений
                UpdateTimer = new System.Threading.Timer((s) => CheckUpdates(), null, 0, Math.Max(MinimumUpdateTimerInterval, Configuration.CheckUpdateInterval));

                CreateMessage("Инициализация и запуск именованного канала...", MessageType.Information, false, false, true);
                NamedPipeListener <string> namedPipeListener = new NamedPipeListener <string>(ProductName);
                namedPipeListener.MessageReceived += delegate(object sender, NamedPipeListenerMessageReceivedEventArgs <string> e) {
                    switch (e.Message)
                    {
                    case "force":
                        TasksHelper.RunTasksThread();
                        break;

                    default:
                        break;
                    }
                };
                namedPipeListener.Error += delegate(object sender, NamedPipeListenerErrorEventArgs e) {
                    CreateMessage(string.Format("Ошибка Pipe: ({0}): {1}", e.ErrorType, e.Exception.Message), MessageType.Error, false, false, true);
                };
                namedPipeListener.Start();

                new System.Threading.Timer(delegate(object state) {
                    if (!UpdatesHelper.VersionSended)
                    {
                        CreateMessage("Отправка информации о текущей версии программы на сервер обновлений...", MessageType.Information, false, false, true);
                        System.Threading.Thread thread = new System.Threading.Thread(delegate() {
                            try {
                                string errorString;
                                if (!UpdatesHelper.SendVersionInformation(Configuration.Updates.ServerName, Configuration.ZipCode, ProductName, Version, out errorString))
                                {
                                    throw new Exception(errorString);
                                }
                                UpdatesHelper.VersionSended = true;
                            }
                            catch (Exception ex) {
                                UpdatesHelper.VersionSended = false;
                                CreateMessage("Ошибка при отправке информации о текущей версии программы:\r\n" + ex.ToString(), MessageType.Error, false, false, true);
                            }
                        });
                        thread.Start();
                    }
                }, null, 0, Math.Max(MinimumUpdateTimerInterval, Configuration.CheckUpdateInterval));

                return(true);
            }
            catch (Exception ex) {
                CreateMessage("Ошибка инициализации программы:\r\n" + ex.ToString(), MessageType.Error, true, true, true);
                return(false);
            }
        }
示例#5
0
        // Инициализация
        private bool Init()
        {
            AppHelper.ConfHelper    = new ConfHelper(Path.Combine(CD, "settings.conf"));
            AppHelper.Configuration = AppHelper.ConfHelper.LoadConfig <Config>();
            if (!AppHelper.ConfHelper.Success)
            {
                MessageBox.Show("Ошибка загрузки конфигурации:\r\n" + AppHelper.ConfHelper.LastError.ToString(), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                AppHelper.Log.Write("Ошибка загрузки конфигурации: " + AppHelper.ConfHelper.LastError.ToString(), Feodosiya.Lib.Logs.MessageType.Error);
                if (AppHelper.ConfHelper.LastError is System.IO.FileNotFoundException ||
                    AppHelper.ConfHelper.LastError is System.Runtime.Serialization.SerializationException)
                {
                    if (MessageBox.Show("Создать файл конфигурации по умолчанию?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        AppHelper.Configuration = new Config();
                        AppHelper.ConfHelper.SaveConfig(AppHelper.Configuration);
                    }
                    else
                    {
                        Load += (s, e) => Application.Exit();
                        return(false);
                    }
                }
                else
                {
                    Load += (s, e) => Application.Exit();
                    return(false);
                }
            }

            // Проверка наличия обновлений
            if (AppHelper.Configuration.Global.CheckUpdates)
            {
                try {
                    string version = FileVersionInfo.GetVersionInfo(ExecutingAssembly.Location).FileVersion;
                    if (UpdatesHelper.CheckUpdates(version))
                    {
                        Process.Start("Updater.exe", string.Format("{0} {1} {2}", version, AppHelper.Configuration.Global.UpdatesServerName, Program.ProductName));

                        Load += (s, e) => Application.Exit();
                        return(false);
                    }
                }
                catch (Exception ex) {
                    AppHelper.Log.Write("Ошибка проверки обновлений: " + ex.ToString(), Feodosiya.Lib.Logs.MessageType.Error);
                }
            }

            AppHelper.Configuration.SingletonEvent.PropertyChangedEvent += new ChangeEventHandler(OnCofigurationChanged);

            StringHelper.Encoding   = Encoding.UTF8;
            StringHelper.PassPhrase = AppHelper.GUID;

            try {
                string path = Assembly.GetExecutingAssembly().Location;

                if (AppHelper.Configuration.Global.EnableAutorun)
                {
                    Feodosiya.Lib.App.AppHelper.AddToAutorun(path);
                }
                else
                {
                    Feodosiya.Lib.App.AppHelper.RemoveFromAutorun(path);
                }
            }
            catch { }

            return(true);
        }
示例#6
0
        private void Frm_Pornire_Loaded(object sender, RoutedEventArgs e)
        {
            string formatNrScurt = "##,##0";
            string formatNrLung  = "##,##0.00";
            // string Settings_XML_File = string.Empty;
            string sPath          = string.Empty;
            string numeFisierVers = string.Empty;

            try
            {
                // Determin locatia unde este fisierul Settings.XML
                string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                // Settings_XML_File = Environment.CurrentDirectory + @"\E_Intrastat'Settings.xml";
                CONSTANTE.Setting_XML_file = path + @"\E_Intrastat\Settings.xml";
                // if (!XML_Operatii.Verifica_Fisier(Settings_XML_File))
                //  {
                //    MessageBox.Show("EROARE identificare fisier setari: " + Settings_XML_File + " nu exista");
                //    return;
                //  }
                XML_Setari_Default.Setari_Default_XML();

                EU_Registrii_Operatii.EU_Registrii();
                XML_Public_Citeste.Citeste_CUlori();
                XML_Public_Citeste.Citeste_Zecimale();
                XML_Public_Citeste.Citeste_FileLocation();
                XML_Public_Citeste.Citeste_Diverse();

                if (Diverse.VerificaUpdate == true)
                {
                    string   versionFilePath  = FileLocation.System + "vers.txt";
                    string[] versionFileLines = File.ReadAllLines(versionFilePath);
                    numeFisierVers = UpdatesHelper.Verifica_Update_Versiune(versionFileLines[0]);
                    if (numeFisierVers != "0")
                    {
                        if (MessageBoxResult.Yes ==
                            MessageBox.Show("Exista o versiune noua pentru descarcare\nDoriti descarcarea si instalarea noii versiuni?", "Info", MessageBoxButton.YesNo))
                        {
                            sPath = Environment.CurrentDirectory + @"UpdateWEB\UpdateWEB.exe";
                            ClasaSuport.StartProgramByFileName(sPath, true);
                            Application.Current.Shutdown();
                            return;
                        }
                    }
                }

                string comunpath = "C:\\E_Intrastat\\System\\DataBase\\Comun.mdb";
                bool   flag      = false;
                if (!Verifica_Exista_Fisier.Verifica_Fisier(comunpath))
                {
                    foreach (var drive in DriveInfo.GetDrives())
                    {
                        if (Verifica_Exista_Fisier.Verifica_Fisier(drive + "E_Intrastat\\System\\DataBase\\Comun.mdb"))
                        // MessageBox.Show("FIșierul a fost gasit!");
                        {
                            XML_Operatii.Actualizare_XML(CONSTANTE.Setting_XML_file, "/Settings/E_Intrastat/Setari/FileLocation", "DataBase", drive + "E_Intrastat\\System\\DataBase\\", true);
                            XML_Operatii.Actualizare_XML(CONSTANTE.Setting_XML_file, "/Settings/E_Intrastat/Setari/FileLocation", "System", drive + "E_Intrastat\\System\\", true);
                            XML_Operatii.Actualizare_XML(CONSTANTE.Setting_XML_file, "/Settings/E_Intrastat/Setari/FileLocation", "DirectorSalvare", drive + "E_Intrastat\\System\\DeclaratiiXML\\", true);
                            XML_Operatii.Actualizare_XML(CONSTANTE.Setting_XML_file, "/Settings/E_Intrastat/Setari/FileLocation", "ReportDefinitionPath", drive + "E_Intrastat\\System\\RaportDefinition", true);

                            flag = true;
                        }
                    }
                }
                else
                {
                    flag = true;
                }
                if (flag == false)
                {
                    MessageBox.Show("Baza de date NU a fost gasita! Exemplu locatie : D:\\E-Intrastat\\System");
                    Application.Current.Shutdown();
                }
                else
                {
                    Update_Curs();
                    Open_Conection_Common();
                    this.Hide();
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("Frm_Pornire_Loaded Error: " + exp.Message);
                Application.Current.Shutdown();
            }
        }