private void doSync()
        {
            if (!CheckPOSSyncDriveExist())
                return;
            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            DialogResult dResult = MessageBox.Show(
                "Bạn muốn xuất hàng cho cửa hàng ? ",
                "Xuất hàng cho cửa hàng", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dResult == DialogResult.No)
            {
                return;
            }

            var configurationAppSettings = new AppSettingsReader();
            //var exportPath = (string)configurationAppSettings.GetValue("SyncExportPath", typeof(String));
            var configExportPath = POSSyncDrive + ClientSetting.SyncExportPath;
            if (string.IsNullOrEmpty(configExportPath) || !Directory.Exists(configExportPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + configExportPath + "!Hãy kiễm tra file cấu hình phần SyncExportPath");
                return;
            }
            resultList = new ArrayList();
            try
            {
                if(chkMasterData.Checked)
                {
                    if(!chkDepartments.Checked && !chkPrdMaster.Checked && !chkPrice.Checked)
                    {
                        MessageBox.Show("Bạn phải chọn ít nhất một thông tin chung để đồng bộ.");
                        return;
                    }
                    DatabaseUtils.LoadMasterData(chkPrdMaster.Checked,chkDepartments.Checked,chkPrice.Checked);
                }

                // sync stock-out to dept
                var deptEvent = new DepartmentStockInEventArgs();
                EventUtility.fireEvent(FillDepartmentEvent, this, deptEvent);

                IList departmentList = deptEvent.DepartmentList;
                foreach (Department department in departmentList)
                {
                    CleanUSBDrive(POSSyncDrive);
                    if(department.DepartmentId != syncDeptId) continue;

                    var exportPath = ClientUtility.EnsureSyncPath(configExportPath, department);
                    DateTime lastSyncTime = ClientUtility.GetLastSyncTime(exportPath, department, ClientUtility.SyncType.SyncDown);
                    deptEvent = new DepartmentStockInEventArgs();
                    deptEvent.LastSyncTime = lastSyncTime;
                    deptEvent.Department = department;
                    EventUtility.fireEvent(LoadDepartmentStockInForExportEvent, this, deptEvent);

                    int countSyncFile = 1;
                    if (deptEvent.SyncFromMainToDepartment != null)
                        //&& deptEvent.SyncFromMainToDepartment.StockOutList != null
                        //&& deptEvent.SyncFromMainToDepartment.StockOutList.Count > 0)
                    {

                        // ++ AMEND : SEPARATE STOCKOUTS AND COMMON INFO

                        //var exportPath = ClientUtility.EnsureSyncPath(configExportPath, department);
                        #region oldsynccode
                        /*string fileName = exportPath + "\\" + department.DepartmentId
                                          + "_SyncDown_"
                                          + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")
                                          + CommonConstants.SERVER_SYNC_FORMAT;
                        SyncResult result = new SyncResult();
                        result.FileName = fileName;
                        result.Status = "Thành công";
                        resultList.Add(result);
                        Stream stream = File.Open(fileName, FileMode.Create);
                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(stream, deptEvent.SyncFromMainToDepartment);
                        stream.Flush();
                        stream.Close();*/

                        #endregion

                        SyncFromMainToDepartment common = new SyncFromMainToDepartment();

                            common.Department = deptEvent.SyncFromMainToDepartment.Department;
                            common.DepartmentList = deptEvent.SyncFromMainToDepartment.DepartmentList;
                            common.EmployeeList = deptEvent.SyncFromMainToDepartment.EmployeeList;
                            common.DepartmentPriceMasterList =
                                deptEvent.SyncFromMainToDepartment.DepartmentPriceMasterList;
                            common.DepartmentStockTemps = deptEvent.SyncFromMainToDepartment.DepartmentStockTemps;
                            common.ProductMasterList = deptEvent.SyncFromMainToDepartment.ProductMasterList;
                            common.UserInfoList = deptEvent.SyncFromMainToDepartment.UserInfoList;

                            string fileName = exportPath + "\\" + department.DepartmentId
                                              + "_" + countSyncFile.ToString()
                                              + "_SyncDown_"
                                              + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")
                                              + CommonConstants.SERVER_SYNC_FORMAT;
                            SyncResult result = new SyncResult();
                            result.FileName = fileName;
                            result.Status = "Thành công";
                            resultList.Add(result);
                            Stream stream = File.Open(fileName, FileMode.Create);
                            BinaryFormatter bf = new BinaryFormatter();
                            bf.Serialize(stream, deptEvent.SyncFromMainToDepartment);
                            stream.Flush();
                            stream.Close();

                        // write each stock out to a sync file for avoiding duplicate update
                        if(deptEvent.SyncFromMainToDepartment.StockOutList!=null
                           && deptEvent.SyncFromMainToDepartment.StockOutList.Count > 0 )
                        {
                            foreach (StockOut stockOut in deptEvent.SyncFromMainToDepartment.StockOutList)
                            {
                                countSyncFile += 1;
                                SyncFromMainToDepartment soSync = new SyncFromMainToDepartment();
                                soSync.Department = deptEvent.SyncFromMainToDepartment.Department;
                                soSync.StockOutList = new ArrayList();
                                soSync.StockOutList.Add(stockOut);

                                string soFileName = exportPath + "\\" + department.DepartmentId
                                              + "_" + countSyncFile.ToString()
                                              + "_SyncDown_"
                                              + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")
                                              + CommonConstants.SERVER_SYNC_FORMAT;
                                SyncResult soResult = new SyncResult();
                                soResult.FileName = soFileName;
                                soResult.Status = "Thành công";
                                resultList.Add(soResult);
                                Stream soStream = File.Open(soFileName, FileMode.Create);
                                BinaryFormatter soBf = new BinaryFormatter();
                                soBf.Serialize(soStream, soSync);
                                soStream.Flush();
                                soStream.Close();
                            }
                        }

                        // -- AMEND : SEPARATE STOCKOUTS AND COMMON INFO
                        // write last sync time
                        //ClientUtility.WriteLastSyncTime(exportPath,department,ClientUtility.SyncType.SyncDown);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            MessageBox.Show("Đồng bộ hoàn tất !");
        }
        private void btnSyncToMain_Click(object sender, EventArgs e)
        {
            if(!CheckPOSSyncDriveExist())
                return;
            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            DialogResult dResult = MessageBox.Show(
                "Bạn muốn xuất hàng cho cửa hàng ? ",
                "Xuất hàng cho cửa hàng", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dResult == DialogResult.No)
            {
                return;
            }

            var configurationAppSettings = new AppSettingsReader();
            //var exportPath = (string)configurationAppSettings.GetValue("SyncExportPath", typeof(String));
            var configExportPath = POSSyncDrive + ClientSetting.SyncExportPath;
            if (string.IsNullOrEmpty(configExportPath) || !Directory.Exists(configExportPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + configExportPath + "!Hãy kiễm tra file cấu hình phần SyncExportPath");
                return;
            }
            IList resultList = new ArrayList();
            try
            {
                var deptEvent = new DepartmentStockInEventArgs();
                EventUtility.fireEvent(FillDepartmentEvent, this, deptEvent);

                IList departmentList = deptEvent.DepartmentList;
                foreach (Department department in departmentList)
                {
                    var exportPath = ClientUtility.EnsureSyncPath(configExportPath, department);
                    DateTime lastSyncTime = ClientUtility.GetLastSyncTime(exportPath,department,ClientUtility.SyncType.SyncDown);
                    deptEvent = new DepartmentStockInEventArgs();
                    deptEvent.LastSyncTime = lastSyncTime;
                    deptEvent.Department = department;
                    EventUtility.fireEvent(LoadDepartemntStockInForExportEvent, this, deptEvent);

                    if(deptEvent.SyncFromMainToDepartment!=null
                        && deptEvent.SyncFromMainToDepartment.StockOutList!=null
                        && deptEvent.SyncFromMainToDepartment.StockOutList.Count > 0 )
                    {
                        string fileName = exportPath + "\\" + department.DepartmentId + "_SyncDown_" +
                                                              DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + CommonConstants.SERVER_SYNC_FORMAT;
                        SyncResult result = new SyncResult();
                        result.FileName = fileName;
                        result.Status = "Thành công";
                        resultList.Add(result);
                        Stream stream = File.Open(fileName, FileMode.Create);
                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(stream, deptEvent.SyncFromMainToDepartment);
                        stream.Close();
                        // write last sync time
                        //ClientUtility.WriteLastSyncTime(exportPath,department,ClientUtility.SyncType.SyncDown);
                    }

                }
            }
            catch (Exception)
            {
                throw;
            }
            MessageBox.Show("Đồng bộ hoàn tất !");
            syncResultBindingSource.DataSource = resultList;
        }
예제 #3
0
        private void doSync()
        {
            if (!CheckPOSSyncDriveExist())
                return;
            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            DialogResult dResult = MessageBox.Show(
                "Bạn muốn tạo hình ảnh dữ liệu ? ",
                "Tạo hình ảnh dữ liệu", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dResult == DialogResult.No)
            {
                return;
            }

            var configurationAppSettings = new AppSettingsReader();
            //var exportPath = (string)configurationAppSettings.GetValue("SyncExportPath", typeof(String));
            var configExportPath = POSSyncDrive + ClientSetting.SyncExportPath;
            if (string.IsNullOrEmpty(configExportPath) || !Directory.Exists(configExportPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + configExportPath + "!Hãy kiễm tra file cấu hình phần SyncExportPath");
                return;
            }
            resultList = new ArrayList();
            try
            {

                DatabaseUtils.LoadMasterData(chkPrdMaster.Checked, chkDepartments.Checked, chkPrice.Checked);
                SyncResult mstResult = new SyncResult();
                mstResult.FileName = "HINH ANH DU LIEU";
                mstResult.Status = "Thành công";
                resultList.Add(mstResult);
                // sync master data first
                /*Department mstDataDept = new Department
                {
                    DepartmentId = 0,
                    DepartmentName = "DataImage"
                };
                //DateTime lastMasterDataSyncTime = ClientUtility.GetLastSyncTime(configExportPath, mstDataDept, ClientUtility.SyncType.SyncDown);
                var masterDataEvent = new DepartmentStockInEventArgs();
                masterDataEvent.LastSyncTime = DateTime.MinValue;
                if(chkMasterData.Checked)
                {
                    masterDataEvent.SyncProductMasters = chkPrdMaster.Checked;
                    masterDataEvent.SyncPrice = chkPrice.Checked;
                    masterDataEvent.SyncDepartments = chkDepartments.Checked;
                }

                EventUtility.fireEvent(LoadMasterDataForExportEvent, this, masterDataEvent);
                if (masterDataEvent.HasMasterDataToSync)
                {
                    string masterDataFileName = configExportPath + "\\" + "DataImage_SyncDown_" +
                                                DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") +
                                                CommonConstants.SERVER_SYNC_FORMAT;

                    Stream mstStream = File.Open(masterDataFileName, FileMode.Create);
                    BinaryFormatter mstBf = new BinaryFormatter();
                    mstBf.Serialize(mstStream, masterDataEvent.SyncFromMainToDepartment);
                    mstStream.Flush();
                    mstStream.Close();
                    SyncResult mstResult = new SyncResult();
                    mstResult.FileName = masterDataFileName;
                    mstResult.Status = "Thành công";
                    resultList.Add(mstResult);
                }*/

            }
            catch (Exception)
            {
                SyncResult mstResult = new SyncResult();
                mstResult.FileName = "Chưa tạo được file image";
                mstResult.Status = "Thất bại";
                resultList.Add(mstResult);
            }
            MessageBox.Show("Đồng bộ hoàn tất !");
        }
예제 #4
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if(!CheckPOSSyncDriveExist())
                return;
            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            bool isConfirmPeriod = false;
            DialogResult dResult = MessageBox.Show(
                "Bạn xác định kết sổ cho ngày hôm nay ? Nếu phải, bấm Yes, còn nếu không, bấm No. Không làm gì, bấm Cancel",
                "Kết sổ", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if(dResult == DialogResult.Cancel)
            {
                return;
            }
            if(dResult== DialogResult.Yes)
            {
                isConfirmPeriod = true;
            }

            // sync
            var configurationAppSettings = new AppSettingsReader();
            syncResultBindingSource.DataSource = null;
            var exportPath = POSSyncDrive + ClientSetting.SyncExportPath;

            if (string.IsNullOrEmpty(exportPath) || !Directory.Exists(exportPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + exportPath + "!Hãy kiễm tra file cấu hình phần SyncExportPath");
                return;
            }

            try
            {
                // dump db
                ClientUtility.DumpDatabase();
                exportPath = ClientUtility.EnsureSyncPath(exportPath, CurrentDepartment.Get());
                // get last sync time
                DateTime lastSyncTime = ClientUtility.GetLastSyncTime(exportPath, CurrentDepartment.Get(),ClientUtility.SyncType.SyncUp);
                SyncResult result = new SyncResult();
                string fileName = exportPath + "\\" + CurrentDepartment.Get().DepartmentId + "_SyncUp_" +
                                  DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + CommonConstants.CLIENT_SYNC_FORMAT;
                var eventArgs = new DepartmentStockOutEventArgs();

                eventArgs.IsConfirmPeriod = isConfirmPeriod;
                eventArgs.LastSyncTime = lastSyncTime;
                EventUtility.fireEvent(GetSyncDataEvent, this, eventArgs);
                SyncFromDepartmentToMain syncData = eventArgs.SyncFromDepartmentToMain;
                if (syncData != null)
                {
                    Stream stream = File.Open(fileName, FileMode.Create);
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(stream, syncData);
                    stream.Close();

                    result.FileName = fileName;
                    result.Status = "Thành công";
                    ClientUtility.CleanDatabase();
                    // write last sync time
                    //ClientUtility.WriteLastSyncTime(exportPath,CurrentDepartment.Get(),ClientUtility.SyncType.SyncUp);
                    MessageBox.Show("Đồng bộ thành công");

                }
                else
                {
                    MessageBox.Show("Đồng bộ thất bại");
                    result.FileName = fileName;
                    result.Status = "Thất bại";
                }
                IList resultList = new ArrayList();
                resultList.Add(result);
                syncResultBindingSource.DataSource = resultList;
            }
            catch (Exception exps)
            {
                if(exps is BusinessException)
                {
                    MessageBox.Show(exps.Message);
                }
                else
                {
                    MessageBox.Show("Có lỗi xảy ra");
                }
                //throw;
            }
            //            }
        }
예제 #5
0
        private void DoSyncFromMain()
        {
            resultList = new ArrayList();
            if (!CheckPOSSyncDriveExist())
            {

                return;
            }

            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            DialogResult dResult = MessageBox.Show(
                "Bạn muốn đồng bộ hình ảnh dữ liệu ? ",
                "Hình ảnh dữ liệu", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dResult == DialogResult.No)
            {
                return;
            }

            var configurationAppSettings = new AppSettingsReader();
            //var importPath = (string)configurationAppSettings.GetValue("SyncImportPath", typeof(String));
            var masterPath = POSSyncDrive + "\\POS"; ///+ClientSetting.SyncExportPath;
            var importPath = POSSyncDrive + ClientSetting.SyncImportPath;
            var successPath = POSSyncDrive + ClientSetting.SyncSuccessPath;
            var errorPath = POSSyncDrive + ClientSetting.SyncErrorPath;
            // get import path of this department
            importPath = importPath + "\\" + CurrentDepartment.Get().DepartmentId;
            //errorPath = ClientUtility.EnsureSyncPath(errorPath, CurrentDepartment.Get());
            //successPath = ClientUtility.EnsureSyncPath(successPath, CurrentDepartment.Get());
            if (string.IsNullOrEmpty(masterPath) || !Directory.Exists(masterPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + masterPath + "!Hãy kiễm tra file cấu hình phần SyncImportPath");

                return;
            }

            if (string.IsNullOrEmpty(successPath) || !Directory.Exists(successPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + successPath + "!Hãy kiễm tra file cấu hình phần SyncImportSuccessPath");

                return;
            }
            //var errorPath = (string)configurationAppSettings.GetValue("SyncImportErrorPath", typeof(String));

            if (string.IsNullOrEmpty(errorPath) || !Directory.Exists(errorPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + errorPath + "!Hãy kiễm tra file cấu hình phần SyncImportErrorPath");

                return;
            }

            // sync master data first
            string[] masterNames = Directory.GetFiles(masterPath, "*.zip");
            if (masterNames.Length > 0)
            {
                // get file name and sync master data
                string masterFileName = "";
                foreach (string masterName in masterNames)
                {
                    masterFileName = masterName;
                    if (!string.IsNullOrEmpty(masterFileName))
                    {
                        SyncResult result = new SyncResult();
                        result.FileName = masterFileName;

                        if (masterFileName.IndexOf("MasterData") < 0)
                        {
                            continue;
                        }
                        resultList.Add(result);
                        try
                        {
                            DatabaseUtils.SyncMasterData(masterFileName);
                            result.Status = "Thành công !";
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            result.Status = "Thất bại!";
                        }
                    }
                }
            }
        }
        private void btnSyncToMain_Click(object sender, EventArgs e)
        {
            if(!CheckPOSSyncDriveExist())
                return;
            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            DialogResult dResult = MessageBox.Show(
                "Bạn muốn đồng bộ từ cửa hàng ? ",
                "Đồng bộ", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dResult == DialogResult.No)
            {
                return;
            }

            var configurationAppSettings = new AppSettingsReader();
            //var importPath = (string)configurationAppSettings.GetValue("SyncImportPath", typeof(String));
            var importPath = POSSyncDrive + ClientSetting.SyncImportPath;
            //var successPath = (string)configurationAppSettings.GetValue("SyncImportSuccessPath", typeof(String));
            //var errorPath = (string)configurationAppSettings.GetValue("SyncImportErrorPath", typeof(String));

            var successPath = POSSyncDrive + ClientSetting.SyncSuccessPath;
            var errorPath = POSSyncDrive + ClientSetting.SyncErrorPath;
            // get import path of this department

            if (string.IsNullOrEmpty(importPath) || !Directory.Exists(importPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + importPath + "!Hãy kiễm tra file cấu hình phần SyncImportPath");
                return;
            }

            if (string.IsNullOrEmpty(successPath) || !Directory.Exists(successPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + successPath + "!Hãy kiễm tra file cấu hình phần SyncImportSuccessPath");
                return;
            }

            if (string.IsNullOrEmpty(errorPath) || !Directory.Exists(errorPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + errorPath + "!Hãy kiễm tra file cấu hình phần SyncImportErrorPath");
                return;
            }

            //string[] fileNames = Directory.GetFiles(importPath, "*"+CommonConstants.CLIENT_SYNC_FORMAT);
            string[] syncDirs  = Directory.GetDirectories(importPath);
            IList fileNames = new ArrayList();
            foreach (string syncDir in syncDirs)
            {
                string[] deptFileNames = Directory.GetFiles(syncDir, "*" + CommonConstants.CLIENT_SYNC_FORMAT);
                foreach (string deptFileName in deptFileNames)
                {
                    fileNames.Add(deptFileName);
                }
            }
            if (fileNames.Count == 0)
            {
                MessageBox.Show("Không thể tìm thấy file nào để đồng bộ");
                return;
            }
            IList resultList = new ArrayList();
            StringBuilder errorStr = new StringBuilder();
            foreach (string fileName in fileNames)
            {
                SyncResult result = new SyncResult();
                result.FileName = fileName;
                resultList.Add(result);
                SyncFromDepartmentToMain deptStockIn = null;
                Stream stream = null;
                bool fail = true;
                try
                {
                    stream = File.Open(fileName, FileMode.Open);
                    BinaryFormatter bf = new BinaryFormatter();
                    deptStockIn = (SyncFromDepartmentToMain)bf.Deserialize(stream);

                    if (deptStockIn == null)
                    {
                        fail = true;
                    }
                    else
                    {
                        var eventArgs = new DepartmentStockOutEventArgs();
                        eventArgs.SyncFromDepartmentToMain = deptStockIn;
                        EventUtility.fireEvent(SyncToMainEvent, this, eventArgs);
                        if (eventArgs.EventResult != null)
                        {
                            fail = false;
                        }
                        else
                        {
                            fail = true;
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                    if (fail)
                    {
                        //File.Move(fileName, errorPath + "\\" + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")));
                        ClientUtility.MoveFileToSpecificDir(errorPath,fileName);
            //                        errorStr.Append("   > " + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")) + "\r\n");
                        result.Status = "Thất bại";
                    }
                    else
                    {
                        //File.Move(fileName, successPath + "\\" + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")));
                        ClientUtility.MoveFileToSpecificDir(successPath, fileName);
                        string origFileName = fileName.Substring(fileName.LastIndexOf("\\") + 1, fileName.Length - (fileName.LastIndexOf("\\") + 1));
                        string[] separateFileNames = origFileName.Split('.');
                        string updateTimeStr =
                            separateFileNames[0].Substring(separateFileNames[0].IndexOf("_SyncUp_") + 8);
                        DateTime updateTime = DateTime.ParseExact(updateTimeStr, "yyyy_MM_dd_HH_mm_ss", null);
                        string syncPath = fileName.Substring(0, fileName.LastIndexOf("\\"));
                        long deptId = Int32.Parse(origFileName.Substring(0, origFileName.IndexOf("_")));
                        Department department = new Department{ DepartmentId = deptId};
                        ClientUtility.WriteLastSyncTime(updateTime, syncPath,department , ClientUtility.SyncType.SyncUp);
                        result.Status = "Thành công";
                    }
                }
            }
            MessageBox.Show("Đồng bộ hoàn tất !");
            syncResultBindingSource.DataSource = resultList;
            //            if (errorStr.Length > 0)
            //            {
            //                MessageBox.Show("Có lỗi diễn ra: \r\n" + errorStr.ToString());
            //            }
            //            else
            //            {
            //
            //            }
            //            var fileOpen = new OpenFileDialog();
            //            fileOpen.InitialDirectory = ".\\";
            //            fileOpen.Filter = "POS (*.xac)|*.xac";
            //            fileOpen.FilterIndex = 0;
            //            fileOpen.RestoreDirectory = true;
            //            if (fileOpen.ShowDialog() == DialogResult.OK)
            //            {
            //                string filePath = fileOpen.FileName;
            //                if (String.IsNullOrEmpty(filePath))
            //                {
            //                    MessageBox.Show("Không tìm thấy file đồng bộ");
            //                    return;
            //                }
            //                if (!File.Exists(filePath))
            //                {
            //                    MessageBox.Show("File đồng bộ không tồn tại");
            //                    return;
            //                }
            //                SyncFromDepartmentToMain deptStockIn = null;
            //                try
            //                {
            //                    Stream stream = File.Open(filePath, FileMode.Open);
            //                    BinaryFormatter bf = new BinaryFormatter();
            //                    deptStockIn = (SyncFromDepartmentToMain)bf.Deserialize(stream);
            //                    stream.Close();
            //
            //                    if (deptStockIn == null)
            //                    {
            //                        MessageBox.Show("File đồng bộ bị lỗi");
            //                        return;
            //                    }
            //                }
            //                catch (Exception)
            //                {
            //                    MessageBox.Show("File đồng bộ bị lỗi");
            //                }
            //                if (deptStockIn != null)
            //                {
            //                    var eventArgs = new DepartmentStockOutEventArgs();
            //                    eventArgs.SyncFromDepartmentToMain = deptStockIn;
            //                    EventUtility.fireEvent(SyncToMainEvent, this, eventArgs);
            //                    if (eventArgs.EventResult != null)
            //                    {
            //                        MessageBox.Show("Đồng bộ hoàn tất !");
            //                    }
            //                    else
            //                    {
            //                        MessageBox.Show("Đồng bộ thất bại!");
            //                    }
            //                }
            //            }
        }
        private void btnSyncToMain_Click(object sender, EventArgs e)
        {
            if(!CheckPOSSyncDriveExist())
            {
                return;
            }

            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            DialogResult dResult = MessageBox.Show(
                "Bạn muốn nhập hàng cho cửa hàng ? ",
                "Nhập hàng cho cửa hàng", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dResult == DialogResult.No)
            {
                return;
            }

            var configurationAppSettings = new AppSettingsReader();
            //var importPath = (string)configurationAppSettings.GetValue("SyncImportPath", typeof(String));
            var importPath = POSSyncDrive + ClientSetting.SyncImportPath;
            var successPath = POSSyncDrive + ClientSetting.SyncSuccessPath;
            var errorPath = POSSyncDrive + ClientSetting.SyncErrorPath;
            // get import path of this department
            importPath = importPath + "\\" + CurrentDepartment.Get().DepartmentId;
            //errorPath = ClientUtility.EnsureSyncPath(errorPath, CurrentDepartment.Get());
            //successPath = ClientUtility.EnsureSyncPath(successPath, CurrentDepartment.Get());

            if (string.IsNullOrEmpty(importPath) || !Directory.Exists(importPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + importPath + "!Hãy kiễm tra file cấu hình phần SyncImportPath");
                return;
            }
            //var successPath = (string)configurationAppSettings.GetValue("SyncImportSuccessPath", typeof(String));

            if (string.IsNullOrEmpty(successPath) || !Directory.Exists(successPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + successPath + "!Hãy kiễm tra file cấu hình phần SyncImportSuccessPath");
                return;
            }
            //var errorPath = (string)configurationAppSettings.GetValue("SyncImportErrorPath", typeof(String));

            if (string.IsNullOrEmpty(errorPath) || !Directory.Exists(errorPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + errorPath + "!Hãy kiễm tra file cấu hình phần SyncImportErrorPath");
                return;
            }

            string[] fileNames = Directory.GetFiles(importPath, "*"+CommonConstants.SERVER_SYNC_FORMAT);
            /*string[] extraFileNames =
                Directory.GetFiles(importPath + "\\" + CurrentDepartment.Get().DepartmentId.ToString(),
                                   "*" + CommonConstants.SERVER_SYNC_FORMAT);*/
            IList fileNameList = new ArrayList();
            if (fileNames.Length == 0 /*&& extraFileNames.Length == 0*/)
            {
                MessageBox.Show("Không thể tìm thấy file nào để đồng bộ");
                return;
            }
            foreach (string fileName in fileNames)
            {
                fileNameList.Add(fileName);
            }
            /*foreach (string extraFileName in extraFileNames)
            {
                fileNameList.Add(extraFileName);
            }*/
            IList resultList = new ArrayList();
            StringBuilder errorStr = new StringBuilder();
            foreach (string fileName in fileNameList)
            {
                SyncResult result = new SyncResult();
                result.FileName = fileName;
                resultList.Add(result);
                DepartmentStockIn deptStockIn = null;
                Stream stream = null;
                bool fail = true;
                try
                {
                    stream = File.Open(fileName, FileMode.Open);
                    BinaryFormatter bf = new BinaryFormatter();
                    SyncFromMainToDepartment syncFMTD = (SyncFromMainToDepartment)bf.Deserialize(stream);
                    Department dept;
                    if (syncFMTD == null || syncFMTD.Department == null)
                    {
                        fail = true;
                    }
                    else
                    {
                        if (CurrentDepartment.CurrentActiveDepartment(out dept)
                         && syncFMTD.Department.DepartmentId == CurrentDepartment.Get().DepartmentId)
                        {
                            var eventArgs = new DepartmentStockInEventArgs();
                            //eventArgs.DepartmentStockIn = deptStockIn;
                            eventArgs.SyncFromMainToDepartment = syncFMTD;
                            EventUtility.fireEvent(SyncDepartmentStockInEvent, this, eventArgs);
                            if (eventArgs.EventResult != null)
                            {
                                fail = false;
                            }
                            else
                            {
                                fail = true;
                            }
                        }
                    }
                    /*deptStockIn = (DepartmentStockIn)bf.Deserialize(stream);
                    Department dept;
                    if (deptStockIn == null
                    || deptStockIn.DepartmentStockInPK == null
                    || (CurrentDepartment.CurrentActiveDepartment(out dept) && deptStockIn.DepartmentStockInPK.DepartmentId != CurrentDepartment.Get().DepartmentId))
                    {
                        fail = true;
                    }
                    else
                    {
                        var eventArgs = new DepartmentStockInEventArgs();
                        eventArgs.DepartmentStockIn = deptStockIn;
                        EventUtility.fireEvent(SyncDepartmentStockInEvent, this, eventArgs);
                        if (eventArgs.EventResult != null)
                        {
                            fail = false;
                        }
                        else
                        {
                            fail = true;
                        }

                    }*/
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                    if (fail)
                    {
                        //File.Move(fileName, errorPath + "\\" + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")));
                        ClientUtility.MoveFileToSpecificDir(errorPath,fileName);
            //                        errorStr.Append("   > " + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")) + "\r\n");
                        result.Status = "Thất bại";
                    }
                    else
                    {
                        //File.Move(fileName, successPath + "\\" + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")));
                        ClientUtility.MoveFileToSpecificDir(successPath, fileName);
                        string origFileName = fileName.Substring(fileName.LastIndexOf("\\")+1, fileName.Length - (fileName.LastIndexOf("\\")+1));
                        string[] separateFileNames = origFileName.Split('.');
                        string updateTimeStr =
                            separateFileNames[0].Substring(separateFileNames[0].IndexOf("_SyncDown_") + 10);
                        DateTime updateTime = DateTime.ParseExact(updateTimeStr, "yyyy_MM_dd_HH_mm_ss", null);
                        ClientUtility.WriteLastSyncTime(updateTime,importPath, CurrentDepartment.Get(), ClientUtility.SyncType.SyncDown);
                        result.Status = "Thành công";
                    }
                }
            }
            MessageBox.Show("Đồng bộ hoàn tất !");
            syncResultBindingSource.DataSource = resultList;
            //            if (errorStr.Length > 0)
            //            {
            //                MessageBox.Show("Có lỗi diễn ra: \r\n" + errorStr.ToString());
            //            }
            //            else
            //            {
            //
            //            }

            //            if (String.IsNullOrEmpty(txtFilePath.Text))
            //            {
            //                MessageBox.Show("Không tìm thấy file đồng bộ");
            //                return;
            //            }
            //            if (!File.Exists(txtFilePath.Text))
            //            {
            //                MessageBox.Show("File đồng bộ không tồn tại");
            //                return;
            //            }
            //            DepartmentStockIn deptStockIn = null;
            //            try
            //            {
            //                Stream stream = File.Open(txtFilePath.Text, FileMode.Open);
            //                BinaryFormatter bf = new BinaryFormatter();
            //                deptStockIn = (DepartmentStockIn)bf.Deserialize(stream);
            //                stream.Close();
            //
            //                if (deptStockIn == null
            //                    || deptStockIn.DepartmentStockInPK == null
            //                    || deptStockIn.DepartmentStockInPK.DepartmentId != CurrentDepartment.Get().DepartmentId)
            //                {
            //                    MessageBox.Show("File đồng bộ bị lỗi");
            //                    return;
            //                }
            //            }
            //            catch (Exception)
            //            {
            //                MessageBox.Show("File đồng bộ bị lỗi");
            //            }
            //            if (deptStockIn != null)
            //            {
            //                var eventArgs = new DepartmentStockInEventArgs();
            //                eventArgs.DepartmentStockIn = deptStockIn;
            //                EventUtility.fireEvent(SyncDepartmentStockInEvent, this, eventArgs);
            //                MessageBox.Show("Đồng bộ hoàn tất !");
            //            }
        }
        private void DoSyncFromMain()
        {
            resultList = new ArrayList();
            if (!CheckPOSSyncDriveExist())
            {

                return;
            }

            string POSSyncDrive = ClientUtility.GetPOSSyncDrives()[0].ToString();
            DialogResult dResult = MessageBox.Show(
                "Bạn muốn nhập hàng cho cửa hàng ? ",
                "Nhập hàng cho cửa hàng", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dResult == DialogResult.No)
            {
                return;
            }

            var configurationAppSettings = new AppSettingsReader();
            //var importPath = (string)configurationAppSettings.GetValue("SyncImportPath", typeof(String));
            var masterPath = POSSyncDrive + "\\POS";
            var importPath = POSSyncDrive + ClientSetting.SyncImportPath;
            var successPath = POSSyncDrive + ClientSetting.SyncSuccessPath;
            var errorPath = POSSyncDrive + ClientSetting.SyncErrorPath;
            // get import path of this department
            importPath = importPath + "\\" + CurrentDepartment.Get().DepartmentId;
            //errorPath = ClientUtility.EnsureSyncPath(errorPath, CurrentDepartment.Get());
            //successPath = ClientUtility.EnsureSyncPath(successPath, CurrentDepartment.Get());
            if (string.IsNullOrEmpty(masterPath) || !Directory.Exists(masterPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + masterPath + "!Hãy kiễm tra file cấu hình phần SyncImportPath");

                return;
            }
            if (string.IsNullOrEmpty(importPath) || !Directory.Exists(importPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + importPath + "!Hãy kiễm tra file cấu hình phần SyncImportPath");

                return;
            }

            if (string.IsNullOrEmpty(importPath) || !Directory.Exists(importPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + importPath + "!Hãy kiễm tra file cấu hình phần SyncImportPath");

                return;
            }
            //var successPath = (string)configurationAppSettings.GetValue("SyncImportSuccessPath", typeof(String));

            if (string.IsNullOrEmpty(successPath) || !Directory.Exists(successPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + successPath + "!Hãy kiễm tra file cấu hình phần SyncImportSuccessPath");

                return;
            }
            //var errorPath = (string)configurationAppSettings.GetValue("SyncImportErrorPath", typeof(String));

            if (string.IsNullOrEmpty(errorPath) || !Directory.Exists(errorPath))
            {
                MessageBox.Show("Không thể tìm thấy đường dẫn đến thư mục " + errorPath + "!Hãy kiễm tra file cấu hình phần SyncImportErrorPath");

                return;
            }

                string[] fileNames = Directory.GetFiles(importPath, "*" + CommonConstants.SERVER_SYNC_FORMAT);

                IList fileNameList = new ArrayList();
                if (fileNames.Length == 0)
                {
                    if (resultList.Count == 0)
                    {
                        MessageBox.Show("Không thể tìm thấy file nào để đồng bộ");
                    }
                    //MessageBox.Show("Đồng bộ hoàn tất !");
                }
                else
                {
                    foreach (string fileName in fileNames)
                    {
                        fileNameList.Add(fileName);
                    }

                    StringBuilder errorStr = new StringBuilder();
                    foreach (string fileName in fileNameList)
                    {
                        SyncResult result = new SyncResult();
                        result.FileName = fileName;
                        resultList.Add(result);
                        DepartmentStockIn deptStockIn = null;
                        Stream stream = null;
                        bool fail = true;
                        try
                        {
                            // need to put a part of master data syncing.

                            stream = File.Open(fileName, FileMode.Open);
                            BinaryFormatter bf = new BinaryFormatter();
                            SyncFromMainToDepartment syncFMTD = (SyncFromMainToDepartment) bf.Deserialize(stream);
                            Department dept;
                            if (syncFMTD == null || syncFMTD.Department == null)
                            {
                                fail = true;
                            }
                            else
                            {
                                if (CurrentDepartment.CurrentActiveDepartment(out dept)
                                    && syncFMTD.Department.DepartmentId == CurrentDepartment.Get().DepartmentId)
                                {
                                    var eventArgs = new DepartmentStockInEventArgs();
                                    //eventArgs.DepartmentStockIn = deptStockIn;
                                    eventArgs.SyncFromMainToDepartment = syncFMTD;
                                    EventUtility.fireEvent(SyncDepartmentStockInEvent, this, eventArgs);
                                    if (eventArgs.EventResult != null)
                                    {
                                        fail = false;
                                    }
                                    else
                                    {
                                        fail = true;
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                            if (fail)
                            {
                                //File.Move(fileName, errorPath + "\\" + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")));
                                ClientUtility.MoveFileToSpecificDir(errorPath, fileName);
                                // errorStr.Append("   > " + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")) + "\r\n");
                                result.Status = "Thất bại";
                            }
                            else
                            {
                                //File.Move(fileName, successPath + "\\" + fileName.Substring(fileName.LastIndexOf("\\"), fileName.Length - fileName.LastIndexOf("\\")));
                                ClientUtility.MoveFileToSpecificDir(successPath, fileName);
                                string origFileName = fileName.Substring(fileName.LastIndexOf("\\") + 1,
                                                                         fileName.Length -
                                                                         (fileName.LastIndexOf("\\") + 1));
                                string[] separateFileNames = origFileName.Split('.');
                                string updateTimeStr =
                                    separateFileNames[0].Substring(separateFileNames[0].IndexOf("_SyncDown_") + 10);
                                DateTime updateTime = DateTime.ParseExact(updateTimeStr, "yyyy_MM_dd_HH_mm_ss", null);
                                ClientUtility.WriteLastSyncTime(updateTime, importPath, CurrentDepartment.Get(),
                                                                ClientUtility.SyncType.SyncDown);
                                result.Status = "Thành công";
                            }
                        }
                    }
                }

                // sync master data last
                string[] masterNames = Directory.GetFiles(masterPath, "*.zip");
                if (masterNames.Length > 0)
                {
                    // get file name and sync master data
                    string masterFileName = "";
                    foreach (string masterName in masterNames)
                    {
                        masterFileName = masterName;
                        if (!string.IsNullOrEmpty(masterFileName))
                        {
                            SyncResult result = new SyncResult();
                            result.FileName = masterFileName;

                            if (masterFileName.IndexOf("MasterData") < 0)
                            {
                                continue;
                            }
                            resultList.Add(result);
                            try
                            {
                                DatabaseUtils.SyncMasterData(masterFileName);
                                result.Status = "Thành công !";
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                                result.Status = "Thất bại!";
                            }
                        }
                    }
                }

            MessageBox.Show("Đồng bộ hoàn tất !");
        }