コード例 #1
0
ファイル: FrmMain.cs プロジェクト: AMM-VSU/scada-mono
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (rbSrez.Checked)
            {
                dataTable = new DataTable("SrezTable");
                SrezAdapter sa = new SrezAdapter();
                sa.FileName = txtFileName.Text;
                sa.Fill(dataTable);
            }
            else if (rbEvent.Checked)
            {
                dataTable = new DataTable("EventTable");
                EventAdapter ea = new EventAdapter();
                ea.FileName = txtFileName.Text;
                ea.Fill(dataTable);
            }
            else // rbBase.Checked
            {
                dataTable = new DataTable("BaseTable");
                BaseAdapter ba = new BaseAdapter();
                ba.FileName = txtFileName.Text;
                ba.Fill(dataTable, true);
            }

            dataGridView.DataSource = dataTable;
        }
コード例 #2
0
        /// <summary>
        /// Loads the users dictionary.
        /// </summary>
        private void LoadUsers()
        {
            users = new Dictionary <string, User>();
            BaseTable <User> tblUser = new BaseTable <User>("User", "UserID", CommonPhrases.UserTable);

            try
            {
                BaseAdapter adapter = new BaseAdapter()
                {
                    Directory = Settings.BaseDATDir,
                    TableName = "user.dat"
                };

                adapter.Fill(tblUser, false);

                foreach (User user in tblUser.EnumerateItems())
                {
                    users[user.Name.Trim().ToLowerInvariant()] = user;
                }
            }
            catch (Exception ex)
            {
                WriteToLog(string.Format(Localization.UseRussian ?
                                         "{0}. Ошибка при загрузке пользователей: {1}" :
                                         "{0}. Error loading users: {1}", Name, ex.ToString()),
                           Log.ActTypes.Exception);
            }
        }
コード例 #3
0
ファイル: ModDbExportLogic.cs プロジェクト: zhiqiang-hu/scada
        /// <summary>
        /// Loads a map of channels and devices.
        /// </summary>
        private bool LoadEntityMap(out EntityMap entityMap)
        {
            try
            {
                BaseTable <InCnl> inCnlTable = new BaseTable <InCnl>("InCnl", "CnlNum", CommonPhrases.InCnlTable);

                BaseAdapter adapter = new BaseAdapter()
                {
                    Directory = Settings.BaseDATDir,
                    TableName = "incnl.dat"
                };

                adapter.Fill(inCnlTable, false);
                entityMap = new EntityMap();
                entityMap.Init(inCnlTable);

                log.WriteAction(Localization.UseRussian ?
                                "Карта каналов и КП загружена" :
                                "Map of channels and devices loaded");
                return(true);
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Localization.UseRussian ?
                                   "Ошибка при загрузке карты каналов и КП" :
                                   "Error loading map of channels and devices");
                entityMap = null;
                return(false);
            }
        }
コード例 #4
0
        /// <summary>
        /// Check user
        /// </summary>
        /// <remarks>Checks username, password and role</remarks>
        public bool ValidateUser(string username, string password, out string errMsg)
        {
            try {
                // check the number of attempts
                if (validateUserAttemptNum > MaxValidateUserAttempts)
                {
                    errMsg = Localization.UseRussian
                        ? "Превышено количество попыток входа"
                        : "Number of login attempts exceeded";
                    return(false);
                }
                else
                {
                    validateUserAttemptNum++;
                }

                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    // opening user table
                    BaseAdapter baseAdapter = new BaseAdapter();
                    var         userTable   = new DataTable();
                    baseAdapter.FileName = Path.Combine(Settings.Directory,
                                                        DirectoryBuilder.GetDirectory(ConfigParts.Base), "user.dat");
                    baseAdapter.Fill(userTable, false);

                    // search and verification of user information
                    userTable.CaseSensitive = false;
                    DataRow[] rows = userTable.Select(string.Format("Name = '{0}'", username));

                    if (rows.Length > 0)
                    {
                        var row = rows[0];
                        if ((string)row["Password"] == password)
                        {
                            if ((int)row["RoleID"] == BaseValues.Roles.App)
                            {
                                validateUserAttemptNum = 0;
                                errMsg = "";
                                return(true);
                            }
                            else
                            {
                                errMsg = Localization.UseRussian ? "Недостаточно прав" : "Insufficient rights";
                                return(false);
                            }
                        }
                    }
                }

                errMsg = Localization.UseRussian
                    ? "Неверное имя пользователя или пароль"
                    : "Invalid username or password";
                return(false);
            } catch (Exception ex) {
                errMsg = Localization.UseRussian ? "Ошибка при проверке пользователя" : "Error validating user";
                log.WriteException(ex, errMsg);
                return(false);
            }
        }
コード例 #5
0
ファイル: FrmMain.cs プロジェクト: southasia/scada
        /// <summary>
        /// Загрузить данные базы конфигурации
        /// </summary>
        private void LoadBase()
        {
            try
            {
                tblInCnl.Clear();
                tblCtrlCnl.Clear();
                tblObj.Clear();
                tblKP.Clear();

                BaseAdapter adapter = new BaseAdapter();
                adapter.Directory = baseDATDir;

                adapter.TableName = "incnl.dat";
                adapter.Fill(tblInCnl, false);

                adapter.TableName = "ctrlcnl.dat";
                adapter.Fill(tblCtrlCnl, false);

                adapter.TableName = "obj.dat";
                adapter.Fill(tblObj, false);

                DataRow row = tblObj.NewRow();
                row["ObjNum"] = 0;
                row["Name"]   = AppPhrases.AllObjItem;
                tblObj.Rows.InsertAt(row, 0);

                adapter.TableName = "kp.dat";
                adapter.Fill(tblKP, false);

                row             = tblKP.NewRow();
                row["KPNum"]    = 0;
                row["Name"]     = AppPhrases.AllKPItem;
                row["KPTypeID"] = 0;
                tblKP.Rows.InsertAt(row, 0);

                baseLoaded = true;
            }
            catch (Exception ex)
            {
                ScadaUtils.ShowError(AppPhrases.LoadBaseError + ":\n" + ex.Message);
                baseLoaded = false;
            }
        }
コード例 #6
0
ファイル: ScadaInstance.cs プロジェクト: ytchhh/scada
        /// <summary>
        /// Проверить пользователя
        /// </summary>
        /// <remarks>Проверяется имя пользователя, пароль и роль</remarks>
        public bool ValidateUser(string username, string password, out string errMsg)
        {
            try
            {
                // проверка количества попыток
                if (validateUserAttemptNum > MaxValidateUserAttempts)
                {
                    errMsg = Localization.UseRussian ?
                             "Превышено количество попыток входа" :
                             "Number of login attempts exceeded";
                    return(false);
                }

                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    // открытие таблицы пользователей
                    BaseAdapter baseAdapter = new BaseAdapter();
                    DataTable   userTable   = new DataTable();
                    baseAdapter.FileName = Path.Combine(Settings.Directory,
                                                        DirectoryBuilder.GetDirectory(ConfigParts.Base), "user.dat");
                    baseAdapter.Fill(userTable, false);

                    // поиск и проверка информации о пользователе
                    userTable.CaseSensitive = false;
                    DataRow[] rows = userTable.Select(string.Format("Name = '{0}'", username));

                    if (rows.Length > 0)
                    {
                        DataRow row = rows[0];
                        if ((string)row["Password"] == password && (int)row["RoleID"] == BaseValues.Roles.Admin)
                        {
                            validateUserAttemptNum = 0;
                            errMsg = "";
                            return(true);
                        }
                    }
                }

                validateUserAttemptNum++;
                errMsg = Localization.UseRussian ?
                         "Неверное имя пользователя или пароль" :
                         "Invalid username or password";
                return(false);
            }
            catch (Exception ex)
            {
                errMsg = Localization.UseRussian ?
                         "Ошибка при проверке пользователя" :
                         "Error validating user";
                log.WriteException(ex, errMsg);
                return(false);
            }
        }
コード例 #7
0
 /// <summary>
 /// Download configuration database table
 /// </summary>
 private static bool LoadDataTable(BaseAdapter baseAdapter, Log errLog, ref DataTable dataTable)
 {
     try {
         baseAdapter.Fill(dataTable, true);
         return(true);
     } catch (Exception ex) {
         string errMsg = AppPhrases.IncorrectFilter + ":\r\n" + ex.Message;
         if (errLog != null)
         {
             errLog.WriteAction(errMsg, Log.ActTypes.Exception);
         }
         ScadaUiUtils.ShowError(errMsg);
         return(false);
     }
 }
コード例 #8
0
ファイル: FrmMain.cs プロジェクト: firebitsbr/scada-36
        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (rbSnapshot.Checked)
                {
                    dataTable = new DataTable("SrezTable");
                    srezTable = new SrezTable();
                    SrezAdapter sa = new SrezAdapter();
                    sa.FileName = txtFileName.Text;
                    sa.Fill(dataTable);
                    sa.Fill(srezTable);
                    dataTable.RowChanged += DataTable_RowChanged;
                    dataTable.Columns["DateTime"].ReadOnly = true;
                    dataTable.Columns["CnlNum"].ReadOnly   = true;
                }
                else if (rbEvent.Checked)
                {
                    dataTable = new DataTable("EventTable");
                    srezTable = null;
                    EventAdapter ea = new EventAdapter();
                    ea.FileName = txtFileName.Text;
                    ea.Fill(dataTable);
                }
                else // rbBase.Checked
                {
                    dataTable = new DataTable("BaseTable");
                    srezTable = null;
                    BaseAdapter ba = new BaseAdapter();
                    ba.FileName = txtFileName.Text;
                    ba.Fill(dataTable, true);
                }

                dataTable.DefaultView.AllowNew  = !rbSnapshot.Checked;
                dataTable.DefaultView.AllowEdit = true;
                dataGridView.DataSource         = dataTable;
            }
            catch (Exception ex)
            {
                dataTable = null;
                ScadaUiUtils.ShowError(ex.Message);
            }
            finally
            {
                ShowRecordCount();
            }
        }
コード例 #9
0
        /// <summary>
        /// Imports the configuration from the specified archive.
        /// </summary>
        public void ImportArchive(string srcFileName, ScadaProject project, Instance instance,
                                  out ConfigParts foundConfigParts)
        {
            if (srcFileName == null)
            {
                throw new ArgumentNullException("srcFileName");
            }
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            foundConfigParts = ConfigParts.None;
            string extractDir = Path.Combine(Path.GetDirectoryName(srcFileName),
                                             Path.GetFileNameWithoutExtension(srcFileName));

            try {
                // extract the configuration
                ExtractArchive(srcFileName, extractDir);

                // import the configuration database
                string srcBaseDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Base));

                if (Directory.Exists(srcBaseDir))
                {
                    foundConfigParts |= ConfigParts.Base;

                    foreach (IBaseTable destTable in project.ConfigBase.AllTables)
                    {
                        string datFileName = Path.Combine(srcBaseDir, destTable.Name.ToLowerInvariant() + ".dat");

                        if (File.Exists(datFileName))
                        {
                            try {
                                BaseAdapter baseAdapter = new BaseAdapter()
                                {
                                    FileName = datFileName
                                };
                                var srcTable = new DataTable();
                                baseAdapter.Fill(srcTable, true);
                                ImportBaseTable(srcTable, destTable);
                            } catch (Exception ex) {
                                throw new ScadaException(string.Format(
                                                             AdminPhrases.ImportBaseTableError, destTable.Name), ex);
                            }
                        }
                    }
                }

                // import the interface files
                string srcInterfaceDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Interface));

                if (Directory.Exists(srcInterfaceDir))
                {
                    foundConfigParts |= ConfigParts.Interface;
                    MergeDirectory(srcInterfaceDir, project.Interface.InterfaceDir);
                }

                // import the Server settings
                if (instance.ServerApp.Enabled)
                {
                    string srcServerDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Server));

                    if (Directory.Exists(srcServerDir))
                    {
                        foundConfigParts |= ConfigParts.Server;
                        MergeDirectory(srcServerDir, instance.ServerApp.AppDir);

                        if (!instance.ServerApp.LoadSettings(out string errMsg))
                        {
                            throw new ScadaException(errMsg);
                        }
                    }
                }

                // import the Communicator settings
                if (instance.CommApp.Enabled)
                {
                    string srcCommDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Comm));

                    if (Directory.Exists(srcCommDir))
                    {
                        foundConfigParts |= ConfigParts.Comm;
                        MergeDirectory(srcCommDir, instance.CommApp.AppDir);

                        if (!instance.CommApp.LoadSettings(out string errMsg))
                        {
                            throw new ScadaException(errMsg);
                        }
                    }
                }

                // import the Webstation settings
                if (instance.WebApp.Enabled)
                {
                    string srcWebDir = Path.Combine(extractDir, DirectoryBuilder.GetDirectory(ConfigParts.Web));

                    if (Directory.Exists(srcWebDir))
                    {
                        foundConfigParts |= ConfigParts.Web;
                        MergeDirectory(srcWebDir, instance.WebApp.AppDir);
                    }
                }
            } catch (Exception ex) {
                throw new ScadaException(AdminPhrases.ImportArchiveError, ex);
            } finally {
                // delete the extracted files
                if (Directory.Exists(extractDir))
                {
                    Directory.Delete(extractDir, true);
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Импортировать архив базы конфигурации (патч)
        /// </summary>
        public static bool ImportArchive(string srcFileName, List <Tables.TableInfo> destTableInfoList,
                                         string logFileName, out bool logCreated, out string msg)
        {
            // проверка аргументов метода
            if (string.IsNullOrWhiteSpace(srcFileName))
            {
                throw new ArgumentException(AppPhrases.ImportFileUndefied);
            }

            if (!File.Exists(srcFileName))
            {
                throw new FileNotFoundException(AppPhrases.ImportFileNotExist);
            }

            if (destTableInfoList == null)
            {
                throw new ArgumentNullException("destTableInfoList");
            }

            logCreated = false;
            StreamWriter writer = null;

            try
            {
                // создание журнала импорта и вывод параметров импорта
                if (!string.IsNullOrEmpty(logFileName))
                {
                    writer     = new StreamWriter(logFileName, false, Encoding.UTF8);
                    logCreated = true;

                    WriteTitle(writer, DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.ImportTitle);
                    writer.WriteLine(AppPhrases.ImportSource + srcFileName);
                }

                using (ZipFile zipFile = ZipFile.Read(srcFileName))
                {
                    // получение словаря всех файлов архива с именами в нижнем регистре
                    Dictionary <string, ZipEntry> zipEntries = new Dictionary <string, ZipEntry>(zipFile.Count);
                    foreach (ZipEntry zipEntry in zipFile)
                    {
                        zipEntries.Add(zipEntry.FileName.ToLowerInvariant(), zipEntry);
                    }

                    // импорт таблиц из тех, которые содержатся в архиве
                    int totalUpdRowCnt = 0;
                    int totalErrRowCnt = 0;
                    int updRowCnt;
                    int errRowCnt;

                    foreach (Tables.TableInfo destTableInfo in destTableInfoList)
                    {
                        if (zipEntries.ContainsKey(destTableInfo.FileName))
                        {
                            using (MemoryStream zipStream = new MemoryStream())
                            {
                                // распаковка архива в поток в памяти
                                ZipEntry zipEntry = zipEntries[destTableInfo.FileName];
                                zipEntry.Extract(zipStream);

                                // загрузка импортируемой таблицы в формате DAT из потока
                                BaseAdapter baseAdapter = new BaseAdapter();
                                DataTable   srcTable    = new DataTable();
                                baseAdapter.Stream          = zipStream;
                                baseAdapter.Stream.Position = 0;

                                try
                                {
                                    baseAdapter.Fill(srcTable, true);
                                }
                                catch (Exception ex)
                                {
                                    throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message);
                                }

                                // импорт таблицы
                                string s;
                                ImportTable(srcTable, destTableInfo, 0, writer, out updRowCnt, out errRowCnt, out s);
                                totalUpdRowCnt += updRowCnt;
                                totalErrRowCnt += errRowCnt;
                            }
                        }
                    }

                    msg = totalErrRowCnt == 0 ? string.Format(AppPhrases.ImportCompleted, totalUpdRowCnt) :
                          string.Format(AppPhrases.ImportCompletedWithErr, totalUpdRowCnt, totalErrRowCnt);

                    // вывод результата в журнал импорта
                    if (logCreated)
                    {
                        writer.WriteLine();
                        WriteTitle(writer, AppPhrases.ImportResult);
                        writer.WriteLine(msg);
                    }

                    if (totalUpdRowCnt > 0)
                    {
                        msg += AppPhrases.RefreshRequired;
                    }
                    return(totalErrRowCnt == 0);
                }
            }
            catch (Exception ex)
            {
                msg = AppPhrases.ImportArchiveError + ":\r\n" + ex.Message;
                try { if (logCreated)
                      {
                          writer.WriteLine(msg);
                      }
                }
                catch { }
                return(false);
            }
            finally
            {
                try { writer.Close(); }
                catch { }
            }
        }
コード例 #11
0
        /// <summary>
        /// Импортировать таблицу базы конфигурации из файла формата DAT
        /// </summary>
        public static bool ImportTable(string srcFileName, Tables.TableInfo destTableInfo,
                                       int minID, int maxID, int newMinID, string logFileName, out bool logCreated, out string msg)
        {
            // проверка аргументов метода
            if (string.IsNullOrWhiteSpace(srcFileName))
            {
                throw new ArgumentException(AppPhrases.ImportFileUndefied);
            }

            if (!File.Exists(srcFileName))
            {
                throw new FileNotFoundException(AppPhrases.ImportFileNotExist);
            }

            if (destTableInfo == null)
            {
                throw new ArgumentNullException("destTableInfo");
            }

            logCreated = false;
            StreamWriter writer = null;

            try
            {
                // создание журнала импорта и вывод параметров импорта
                if (!string.IsNullOrEmpty(logFileName))
                {
                    writer     = new StreamWriter(logFileName, false, Encoding.UTF8);
                    logCreated = true;

                    WriteTitle(writer, DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.ImportTitle);
                    writer.WriteLine(AppPhrases.ImportSource + srcFileName);
                }

                // загрузка импортируемой таблицы в формате DAT
                BaseAdapter baseAdapter = new BaseAdapter();
                DataTable   srcTable    = new DataTable();
                baseAdapter.FileName = srcFileName;

                try
                {
                    baseAdapter.Fill(srcTable, true);
                }
                catch (Exception ex)
                {
                    throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message);
                }

                // ограничение диапазона идентификаторов
                string idColName = destTableInfo.IDColName;
                if ((0 < minID || maxID < int.MaxValue) && idColName != "")
                {
                    srcTable.DefaultView.RowFilter = string.Format("{0} <= {2} and {2} <= {1}",
                                                                   minID, maxID, idColName);
                }
                int shiftID = newMinID > 0 ? newMinID - minID : 0;

                // импорт таблицы
                int updRowCnt;
                int errRowCnt;
                ImportTable(srcTable, destTableInfo, shiftID, writer, out updRowCnt, out errRowCnt, out msg);

                if (updRowCnt > 0)
                {
                    msg += AppPhrases.RefreshRequired;
                }
                return(errRowCnt == 0);
            }
            catch (Exception ex)
            {
                msg = AppPhrases.ImportTableError + ":\r\n" + ex.Message;
                try { if (logCreated)
                      {
                          writer.WriteLine(msg);
                      }
                }
                catch { }
                return(false);
            }
            finally
            {
                try { writer.Close(); }
                catch { }
            }
        }
コード例 #12
0
        /// <summary>
        /// Импортировать все таблицы базы конфигурации из заданной директории
        /// </summary>
        public static bool ImportAllTables(string srcDir, List <Tables.TableInfo> destTableInfoList,
                                           string logFileName, out bool logCreated, out string msg)
        {
            // проверка аргументов метода
            if (srcDir == null)
            {
                throw new ArgumentNullException("srcDir");
            }

            if (destTableInfoList == null)
            {
                throw new ArgumentNullException("destTableInfoList");
            }

            if (logFileName == null)
            {
                throw new ArgumentNullException("logFileName");
            }

            logCreated = false;
            StreamWriter writer = null;

            try
            {
                // создание журнала импорта и вывод параметров импорта
                writer     = new StreamWriter(logFileName, false, Encoding.UTF8);
                logCreated = true;
                AppUtils.WriteTitle(writer, DateTime.Now.ToString("G", Localization.Culture) + " " +
                                    AppPhrases.ImportTitle);
                writer.WriteLine(AppPhrases.ImportSource + srcDir);

                // проверка существования импортируемой директории
                if (!Directory.Exists(srcDir))
                {
                    throw new DirectoryNotFoundException(AppPhrases.ImportDirNotExist);
                }

                // импорт таблиц, файлы которых существуют в заданной директории
                int totalUpdRowCnt = 0;
                int totalErrRowCnt = 0;
                int updRowCnt;
                int errRowCnt;
                srcDir = ScadaUtils.NormalDir(srcDir);

                foreach (Tables.TableInfo destTableInfo in destTableInfoList)
                {
                    string srcFileName = srcDir + destTableInfo.FileName;

                    if (File.Exists(srcFileName))
                    {
                        // загрузка импортируемой таблицы в формате DAT
                        BaseAdapter baseAdapter = new BaseAdapter();
                        DataTable   srcTable    = new DataTable();
                        baseAdapter.FileName = srcFileName;

                        try
                        {
                            baseAdapter.Fill(srcTable, true);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message);
                        }

                        // импорт таблицы
                        string s;
                        ImportTable(srcTable, destTableInfo, 0, writer, out updRowCnt, out errRowCnt, out s);
                        totalUpdRowCnt += updRowCnt;
                        totalErrRowCnt += errRowCnt;
                    }
                }

                msg = totalErrRowCnt == 0 ? string.Format(AppPhrases.ImportCompleted, totalUpdRowCnt) :
                      string.Format(AppPhrases.ImportCompletedWithErr, totalUpdRowCnt, totalErrRowCnt);

                // вывод результата в журнал импорта
                writer.WriteLine();
                AppUtils.WriteTitle(writer, AppPhrases.ImportResult);
                writer.WriteLine(msg);

                if (totalUpdRowCnt > 0)
                {
                    msg += AppPhrases.RefreshRequired;
                }
                return(totalErrRowCnt == 0);
            }
            catch (Exception ex)
            {
                msg = AppPhrases.ImportAllTablesError + ":\r\n" + ex.Message;
                try { if (logCreated)
                      {
                          writer.WriteLine(msg);
                      }
                }
                catch { }
                return(false);
            }
            finally
            {
                try { writer.Close(); }
                catch { }
            }
        }
コード例 #13
0
        private void btnImport_Click(object sender, EventArgs e)
        {
            // импорт выбранной таблицы из формата DAT
            StreamWriter writer      = null;
            bool         writeLog    = chkImportLog.Checked;
            bool         logCreated  = false;
            string       logFileName = AppData.ExeDir + "ScadaAdminImport.txt";

            try
            {
                Tables.TableInfo tableInfo = cbTable.SelectedItem as Tables.TableInfo;

                if (tableInfo != null && AppData.Connected)
                {
                    string fileName = txtFileName.Text.Trim();

                    if (writeLog)
                    {
                        writer     = new StreamWriter(logFileName, false, Encoding.Default);
                        logCreated = true;

                        string title = DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.ImportTitle;
                        writer.WriteLine(title);
                        writer.WriteLine(new string('-', title.Length));
                        writer.WriteLine(AppPhrases.ImportTable + tableInfo.Name + " (" + tableInfo.Header + ")");
                        writer.WriteLine(AppPhrases.ImportFile + fileName);
                        writer.WriteLine();
                    }

                    // загрузка импортируемой таблицы
                    BaseAdapter baseAdapter = new BaseAdapter();
                    DataTable   srcTable    = new DataTable();
                    baseAdapter.FileName = fileName;

                    try
                    {
                        baseAdapter.Fill(srcTable, true);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message);
                    }

                    if (writeLog)
                    {
                        writer.WriteLine(AppPhrases.SrcTableFields);
                        writer.WriteLine(new string('-', AppPhrases.SrcTableFields.Length));
                        if (srcTable.Columns.Count > 0)
                        {
                            foreach (DataColumn column in srcTable.Columns)
                            {
                                writer.WriteLine(column.ColumnName + " (" + column.DataType + ")");
                            }
                        }
                        else
                        {
                            writer.WriteLine(AppPhrases.NoFields);
                        }
                        writer.WriteLine();
                    }

                    // определение схемы таблицы БД
                    DataTable destTable = new DataTable(tableInfo.Name);
                    Tables.FillTableSchema(destTable);

                    if (writeLog)
                    {
                        writer.WriteLine(AppPhrases.DestTableFields);
                        writer.WriteLine(new string('-', AppPhrases.DestTableFields.Length));
                        if (destTable.Columns.Count > 0)
                        {
                            foreach (DataColumn column in destTable.Columns)
                            {
                                writer.WriteLine(column.ColumnName + " (" + column.DataType + ")");
                            }
                        }
                        else
                        {
                            writer.WriteLine(AppPhrases.NoFields);
                        }
                        writer.WriteLine();
                    }

                    // установка контроля идентификаторов
                    string firstColumnName = destTable.Columns.Count > 0 ? destTable.Columns[0].ColumnName : "";
                    bool   firstColumnIsID = gbIDs.Enabled && (firstColumnName.EndsWith("ID") ||
                                                               firstColumnName.EndsWith("Num") || firstColumnName == "CnlStatus") &&
                                             destTable.Columns[0].DataType == typeof(int);

                    bool checkMinID = chkStartID.Checked && firstColumnIsID;
                    bool checkMaxID = chkFinalID.Checked && firstColumnIsID;
                    bool shiftID    = chkNewStartID.Checked && firstColumnIsID;
                    bool shiftDef   = false; // смещение определено
                    bool checkID    = checkMaxID || checkMinID || shiftID;

                    int minID      = checkMinID ? Convert.ToInt32(numStartID.Value) : 0;
                    int maxID      = checkMaxID ? Convert.ToInt32(numFinalID.Value) : 0;
                    int newStartID = shiftID ? Convert.ToInt32(numNewStartID.Value) : 0;
                    int shift      = 0;

                    // заполнение таблицы БД
                    foreach (DataRow row in srcTable.Rows)
                    {
                        DataRow newRow  = destTable.NewRow();
                        bool    rowIsOk = true;

                        foreach (DataColumn column in destTable.Columns)
                        {
                            int ind = srcTable.Columns.IndexOf(column.ColumnName);
                            if (ind >= 0 && column.DataType == srcTable.Columns[ind].DataType)
                            {
                                object val = row[ind];
                                if (ind == 0 && checkID && val != null && val != DBNull.Value)
                                {
                                    // проверка идентификатора
                                    int id = (int)val;
                                    if (checkMinID && id < minID || checkMaxID && id > maxID)
                                    {
                                        rowIsOk = false;
                                        break;
                                    }

                                    if (shiftID && !shiftDef)
                                    {
                                        shift    = newStartID - id;
                                        shiftDef = true;
                                    }

                                    newRow[column] = id + shift;
                                }
                                else
                                {
                                    newRow[column] = val;
                                }
                            }
                        }

                        if (rowIsOk)
                        {
                            destTable.Rows.Add(newRow);
                        }
                    }

                    // сохранение информации в БД
                    int       updRows     = 0;
                    int       errRows     = 0;
                    DataRow[] rowsInError = null;

                    try
                    {
                        SqlCeDataAdapter sqlAdapter = destTable.ExtendedProperties["DataAdapter"] as SqlCeDataAdapter;
                        updRows = sqlAdapter.Update(destTable);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(AppPhrases.WriteDBError + ":\r\n" + ex.Message);
                    }

                    if (destTable.HasErrors)
                    {
                        rowsInError = destTable.GetErrors();
                        errRows     = rowsInError.Length;
                    }

                    string msg;
                    if (errRows == 0)
                    {
                        msg = string.Format(AppPhrases.ImportCompleted, updRows);
                        ScadaUtils.ShowInfo(updRows > 0 ? msg + AppPhrases.RefreshRequired : msg);
                    }
                    else
                    {
                        msg = string.Format(AppPhrases.ImportCompletedWithErr, updRows, errRows);
                        AppData.ErrLog.WriteAction(msg, Log.ActTypes.Error);
                        ScadaUtils.ShowError(updRows > 0 ? msg + AppPhrases.RefreshRequired : msg);
                    }

                    if (writeLog)
                    {
                        writer.WriteLine(AppPhrases.ImportResult);
                        writer.WriteLine(new string('-', AppPhrases.ImportResult.Length));
                        writer.WriteLine(msg);

                        if (errRows > 0)
                        {
                            writer.WriteLine();
                            writer.WriteLine(AppPhrases.ImportErrors);
                            writer.WriteLine(new string('-', AppPhrases.ImportErrors.Length));

                            foreach (DataRow row in rowsInError)
                            {
                                if (firstColumnIsID)
                                {
                                    object objVal = row[0];
                                    string strVal = objVal == null || objVal == DBNull.Value ? "NULL" : objVal.ToString();
                                    writer.Write(firstColumnName + " = " + strVal + " : ");
                                }
                                writer.WriteLine(row.RowError);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string errMsg = AppPhrases.ImportError + ":\r\n" + ex.Message;
                try { if (writeLog)
                      {
                          writer.WriteLine(errMsg);
                      }
                }
                catch { }
                AppUtils.ProcError(errMsg);
            }
            finally
            {
                try { writer.Close(); }
                catch { }
            }

            if (writeLog && logCreated)
            {
                Process.Start(logFileName);
            }
        }