using System; using System.Data; using System.IO; using System.Text; using System.Windows.Forms; using ChvSqlCore; namespace MT4TSyncUCLib { public partial class ctrlSync : UserControl { /// /// Максимум символов в лог-text /// private static readonly int M_MAX_TEXT_LOG_CHARS = 100000; /// /// Обратный слэш /// private static readonly char SLASH = '\\'; /// /// Таблица терминалов для обновления /// private DataTable m_dtDestTerminals = null; /// /// current index of the m_dtDestTerminals data /// private int m_iDestTerminalsIndex = 0; /// /// таблица расширений файлов для копирования /// private DataTable m_dtCopyExtentions = null; /// /// Флаг занятости метода таймера /// private bool m_bTimerBusy = false; /// /// Исходный терминал для обновления /// private DataTable m_dtSourceTerminal = null; public ctrlSync() { InitializeComponent(); } private void ctrlSync_Load(object sender, EventArgs e) { showUserProfile(); } private void addToLog(string arg) { string ret = string.Format("{0}: {1}", DateTime.Now.ToString(), arg); string s = string.Format("{0}\r\n{1}", ret, txtLog.Text); if (s.Length > M_MAX_TEXT_LOG_CHARS) txtLog.Text = s.Substring(0, M_MAX_TEXT_LOG_CHARS); else txtLog.Text = s; } private void addErrorLog(string arg) { string ret = string.Format("{0}: {1}", DateTime.Now.ToString(), arg); string s = string.Format("{0}\r\n{1}", ret, txtLogErrors.Text); if (s.Length > M_MAX_TEXT_LOG_CHARS) txtLogErrors.Text = s.Substring(0, M_MAX_TEXT_LOG_CHARS); else txtLogErrors.Text = s; } private void btnStart_Click(object sender, EventArgs e) { object oUserID = aaGetSetObject1.UserProfileGetObject("UserProfile.ID"); if (oUserID == null) { MessageBox.Show("Не задан пользователь", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // get Dest terminals list int userID = (int)oUserID; string sSql = string.Format("select * from DestinationTerminal where [ID_UserProfile] = {0} ORDER BY [ID]" , userID); string conn = DbConnCore.getConnectionString(aaGetSetObject1); m_dtDestTerminals = SqlHelper.ExecuteDataTableCe(conn, CommandType.Text, sSql); // check dest MT4 count if (m_dtDestTerminals.Rows.Count < 1) { MessageBox.Show("Нет конечных терминалов для обновления" , "Сообщение", MessageBoxButtons.OK , MessageBoxIcon.Information); return; } // get source terminal data sSql = string.Format("select * from SourceTerminal where [ID_UserProfile] = {0} ORDER BY [ID]", userID); m_dtSourceTerminal = SqlHelper.ExecuteDataTableCe(conn, CommandType.Text, sSql); // check dest MT4 count if (m_dtSourceTerminal.Rows.Count < 1) { MessageBox.Show("Нет исходного терминала для обновления" , "Сообщение", MessageBoxButtons.OK , MessageBoxIcon.Information); return; } addToLog("Исходный терминал: " + (string)m_dtSourceTerminal.Rows[0]["Path"]); // set progressBar1 range progressBar1.Minimum = 0; progressBar1.Maximum = m_dtDestTerminals.Rows.Count - 1; progressBar1.Value = 0; // current index of the m_dtDestTerminals data m_iDestTerminalsIndex = 0; // check source dir FileInfo fiSourceTerminal = new FileInfo((string)m_dtSourceTerminal.Rows[0]["Path"]); DirectoryInfo diSourcePath = new DirectoryInfo(fiSourceTerminal.DirectoryName); // FileInfo[] logs = di.GetFiles(); if (!diSourcePath.Exists) { addErrorLog(string.Format("Исходный путь не существует: {0}", diSourcePath.FullName)); return; } m_dtCopyExtentions = SqlHelper.ExecuteDataTableCe(conn, CommandType.Text, "select * from CopyExtentions ORDER BY [ID]"); // lock buttons btnStart.Enabled = false; btnSetUserProfile.Enabled = false; progressBar1.Visible = true; btnStop.Enabled = true; aaGetSetObject1.MenuLock(false, false); // lock menu txtLogErrors.Text = ""; addToLog("Копирование файлов включено"); // set file-copying timer setTimer(); } private void btnStop_Click(object sender, EventArgs e) { endCopy("прервано"); } private void endCopy(string sWhy) { btnStop.Enabled = false; btnSetUserProfile.Enabled = true; progressBar1.Visible = false; btnStart.Enabled = true; aaGetSetObject1.MenuLock(true, true); // unlock menu addToLog(string.Format("Копирование файлов {0}", sWhy)); statusBarLabel.Text = string.Format("Готово, обработано терминалов: {0}", m_iDestTerminalsIndex); resetTimer(); } private void setTimer() { timerCopy.Interval = 600; timerCopy.Enabled = true; } private void resetTimer() { timerCopy.Enabled = false; } private void timerCopy_Tick(object sender, EventArgs e) { timerStep(); } /// /// Один шаг таймера // /// private void timerStep() { if (m_bTimerBusy) return; m_bTimerBusy = true; txtLog.Invalidate(); txtLogErrors.Invalidate(); try { //statusBarLabel.Text = DateTime.Now.ToString(); // m_iDestTerminalsIndex - индекс текущего терминала в m_dtDestTerminals DataRow currentDestRow = m_dtDestTerminals.Rows[m_iDestTerminalsIndex]; FileInfo fiDestTerminal = new FileInfo((string)currentDestRow["Path"]); DirectoryInfo diDestTerminalPath = new DirectoryInfo(fiDestTerminal.DirectoryName); string s; s = string.Format("Обработка конечной папки: {0}", diDestTerminalPath.FullName); statusBarLabel.Text = s; addToLog(s); if (!diDestTerminalPath.Exists) { addErrorLog(string.Format("Конечный путь не существует: {0}", diDestTerminalPath.FullName)); return; } // make sync copy of the terminal files foreach (DataRow row in m_dtCopyExtentions.Rows) { string CopyExt; bool IncludeSubFolders; CopyExt = (string)row["PathExt"]; IncludeSubFolders = (bool)row["IncludeSubFolders"]; //statusBarLabel.Text = "Расширение: " + CopyExt; //statusBarLabel.Invalidate(); //statusStrip1.Invalidate(true); //System.Threading.Thread.Sleep(500); // разделить CopyExt на имя подпапки (если есть) и расширение string sAddPath, sFileMask; breakPathAndMask(CopyExt, out sAddPath, out sFileMask); string sSourPath, sDestPath; FileInfo fiSourceTerminal = new FileInfo((string)m_dtSourceTerminal.Rows[0]["Path"]); DirectoryInfo diSourcePath = new DirectoryInfo(fiSourceTerminal.DirectoryName); sSourPath = makeFileSystemPath(diSourcePath.FullName, sAddPath); sDestPath = makeFileSystemPath(diDestTerminalPath.FullName, sAddPath); // start directory copy coreCopyFiles(sSourPath, sDestPath, sFileMask, IncludeSubFolders); } } catch (Exception ex) { addErrorLog(string.Format("Exception: {0}. Источник: {1}", ex.Message, ex.Source)); } finally { // next dest record progressBar1.Increment(1); progressBar1.Invalidate(); //if (progressBar1.Value >= progressBar1.Maximum) // progressBar1.Value = progressBar1.Minimum; m_iDestTerminalsIndex++; if (m_iDestTerminalsIndex >= m_dtDestTerminals.Rows.Count) { // end of processing endCopy("завершено"); } m_bTimerBusy = false; } } /// /// разделить CopyExt на имя подпапки (если есть) и расширение /// private static void breakPathAndMask(string CopyExt, out string sPath, out string sFileMask) { int pos1 = CopyExt.LastIndexOf(@"\"); if (pos1 < 0) { // only mask sPath = ""; sFileMask = CopyExt; return; } sPath = CopyExt.Substring(0, pos1); sFileMask = CopyExt.Substring(pos1 + 1); } private static string makeFileSystemPath(string sFirst, string sSecond) { StringBuilder sb = new StringBuilder(sFirst); if (sFirst[sFirst.Length - 1] != SLASH) sb.Append(SLASH); sb.Append(sSecond); return (sb.ToString()); } /// /// Копировать файлы из исходной папки в конечную. /// /// /// /// /// private void coreCopyFiles(string sSourPath, string sDestPath, string sFileMask, bool bSubfolders) { DirectoryInfo diSour = new DirectoryInfo(sSourPath); DirectoryInfo diDest = new DirectoryInfo(sDestPath); if (!diDest.Exists) diDest.Create(); int filesCount = 0; // files foreach (FileInfo fi in diSour.GetFiles(sFileMask, SearchOption.TopDirectoryOnly)) { string sFileName, sSourName, sDestName; sFileName = fi.Name; sSourName = makeFileSystemPath(diSour.FullName, sFileName); sDestName = makeFileSystemPath(diDest.FullName, sFileName); try { // copy file // File.Copy(sSourName, sDestName, true); //addToLog(string.Format("{0} -> {1}", sSourName, sDestName)); filesCount++; } catch(Exception ex) { addErrorLog(string.Format("ERROR copy file: {0}. Exception: {1}", sSourName, ex.Message)); } } // add to log non-empty copying if (filesCount > 0) addToLog(string.Format("Папки: {0} --> {1} ({2} файлов: {3})", sSourPath, sDestPath, sFileMask, filesCount)); // subfolders if (bSubfolders) { foreach (DirectoryInfo di in diSour.GetDirectories()) { sSourPath = makeFileSystemPath(diSour.FullName, di.Name); sDestPath = makeFileSystemPath(diDest.FullName, di.Name); // call for subfolder coreCopyFiles(sSourPath, sDestPath, sFileMask, bSubfolders); } } } private void showUserProfile() { object oUserID = aaGetSetObject1.UserProfileGetObject("UserProfile.ID"); if (oUserID == null) { // выбрать UserProfile // frmSetUserProfile frm = new frmSetUserProfile(aaGetSetObject1); if (frm.ShowDialog() != DialogResult.OK) { toolBar1.Enabled = false; return; } } string sUserLogin = (string)aaGetSetObject1.UserProfileGetObject("UserProfile.Login"); lbUserProfile.Text = string.Format("Логин: {0}", sUserLogin); } private void btnSetUserProfile_Click(object sender, EventArgs e) { // выбрать UserProfile // frmSetUserProfile frm = new frmSetUserProfile(aaGetSetObject1); if (frm.ShowDialog() == DialogResult.OK) { showUserProfile(); //MT4RefreshData(); } } } }