Exemple #1
0
        private void m_PathWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            //GlobalDefines.m_swchGlobal.Restart();

            LastException = null;

            AutoResetEvent hFinishedSearchEvent = null;
            Thread         th = null;

            if ((DBManagerApp.MainWnd as DispatcherObject).CheckAccess())
            {
                CWaitingWnd.ShowAsync(out hFinishedSearchEvent,
                                      out th,
                                      DBManagerApp.MainWnd.Title,
                                      string.Format(Properties.Resources.resfmtScanningFile, e.FullPath),
                                      DBManagerApp.MainWnd);
            }

            lock (EventsCS)
            {
                if (State != enScanningThreadState.Worked)
                {
                    return;
                }

                CFileScanner Scanner;
                if (m_FileScanners.TryGetValue(e.FullPath, out Scanner))
                {
                    m_PathWatcher.EnableRaisingEvents = false; // т.к. в XMLFileChanged может быть перезапись файла, обрабатывать которую не нужно

                    List <CDataChangedInfo> MadeChanges = Scanner.XMLFileChanged();
                    if (MadeChanges != null)
                    {
                        try
                        {
                            DBManagerApp.m_Entities.SaveChanges();
                        }
                        catch
                        { }

                        RaiseDataChangedEvent(new DataChangedEventArgs(MadeChanges));
                    }

                    m_PathWatcher.EnableRaisingEvents = true;
                }
            }

            if (hFinishedSearchEvent != null)
            {
                hFinishedSearchEvent.Set();
            }
        }
Exemple #2
0
        private void m_PathWatcher_Created(object sender, FileSystemEventArgs e)
        {
            LastException = null;

            AutoResetEvent hFinishedSearchEvent = null;
            Thread         th = null;

            if ((DBManagerApp.MainWnd as DispatcherObject).CheckAccess())
            {
                CWaitingWnd.ShowAsync(out hFinishedSearchEvent,
                                      out th,
                                      DBManagerApp.MainWnd.Title,
                                      string.Format(Properties.Resources.resfmtScanningFile, e.FullPath),
                                      DBManagerApp.MainWnd);
            }

            lock (EventsCS)
            {
                if (State != enScanningThreadState.Worked)
                {
                    return;
                }

                m_PathWatcher.EnableRaisingEvents = false;

                CFileScanner Scanner;
                if (m_FileScanners.TryGetValue(e.FullPath, out Scanner))
                {
                    Scanner.Start(e.FullPath);
                }
                else
                {
                    Scanner = new CFileScanner(e.FullPath, this, false);
                    if (Scanner.State == enScanningThreadState.Worked)
                    {
                        m_FileScanners.Add(e.FullPath, Scanner);
                    }
                }

                DBManagerApp.m_Entities.SaveChanges();

                m_PathWatcher.EnableRaisingEvents = true;
            }

            if (hFinishedSearchEvent != null)
            {
                hFinishedSearchEvent.Set();
            }
        }
Exemple #3
0
        /// <summary>
        /// Остановить сканирование
        /// </summary>
        public override void Stop(bool OnRestart)
        {
            LastException = null;

            AutoResetEvent hFinishedSearchEvent = null;
            Thread         th = null;

            if ((DBManagerApp.MainWnd as DispatcherObject).CheckAccess())
            {
                CWaitingWnd.ShowAsync(out hFinishedSearchEvent,
                                      out th,
                                      DBManagerApp.MainWnd.Title,
                                      string.Format(Properties.Resources.resfmtStoppingDirScanningThread, ScanningPath),
                                      DBManagerApp.MainWnd);
            }

            lock (EventsCS)     // Ждём, когда завершаться все события
            {
                if (State != enScanningThreadState.Stopped)
                {
                    m_PathWatcher.EnableRaisingEvents = false; // Останавливаем сканирование
                    ScanningPath = "";

                    foreach (KeyValuePair <string, CFileScanner> Scanner in m_FileScanners)
                    {
                        Scanner.Value.Stop(false);
                    }

                    State = enScanningThreadState.Stopped;
                }

                if (OnRestart)
                {
                    m_FileScanners.Clear();
                    CompId = GlobalDefines.DEFAULT_XML_INT_VAL;
                }
            }

            if (hFinishedSearchEvent != null)
            {
                hFinishedSearchEvent.Set();
            }
        }
Exemple #4
0
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckSettings())
            {
                return;
            }

            var dataExtractor = new LocalWorkbookDataExtractor();
            var generator     = new WorkbookGenerator(dataExtractor);

            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                               string.Format(Properties.Resources.resImportingCompetitions,
                                                                                                             SelectedComp.Name,
                                                                                                             SelectedComp.DestCompFolder),
                                                                                               this,
                                                                                               CheckAccess()),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                string errorMessage = null;
                if (!dataExtractor.Extract(SelectedComp, CompGroups, out errorMessage))
                {
                    MessageBox.Show(this,
                                    string.Format(Properties.Resources.resfmtCouldNotExtractDataFromRemoteDB, errorMessage),
                                    AppAttributes.Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return;
                }

                if (!generator.Generate(out errorMessage,
                                        arg =>
                                        CWaitingWnd.SetPrompt(((ShowAsyncResult)wrapper).WndID,
                                                              string.Format(Properties.Resources.resImportingCompetitionsWithGroupName,
                                                                            SelectedComp.Name,
                                                                            SelectedComp.DestCompFolder,
                                                                            arg.Key.Name))))
                {
                    MessageBox.Show(this,
                                    string.Format(Properties.Resources.resfmtCouldNotExtractDataToWbks, errorMessage),
                                    AppAttributes.Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return;
                }

                // Показываем книгу в проводнике
                Process.Start(SelectedComp.DestCompFolder);

                MessageBox.Show(this,
                                Properties.Resources.resDataIsExtractedToWbksSuccessfully,
                                AppAttributes.Title,
                                MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }
        }
Exemple #5
0
        private void RefreshSheetNames()
        {
            if (!File.Exists(SelectedComp.SourceWorkbookName) ||
                System.IO.Path.GetExtension(SelectedComp.SourceWorkbookName) == GlobalDefines.MAIN_WBK_EXTENSION ||
                System.IO.Path.GetExtension(SelectedComp.SourceWorkbookName) == GlobalDefines.XLS_EXTENSION ||
                System.IO.Path.GetExtension(SelectedComp.SourceWorkbookName) == GlobalDefines.XLSX_EXTENSION)
            {
                SheetNames.Clear();

                using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                                   Properties.Resources.resGettingSheetNames,
                                                                                                   this,
                                                                                                   CheckAccess()),
                                                                             asyncResult =>
                {
                    if (asyncResult?.hFinishedSearchEvent != null)
                    {
                        asyncResult.hFinishedSearchEvent.Set();
                    }
                }))
                {
                    try
                    {
                        using (var excelApp = new DisposableWrapper <ExcelApplicationEx>(GlobalDefines.StartExcel(),
                                                                                         app =>
                        {
                            if (app != null)
                            {
                                app.App.DisplayAlerts = true;

                                if (app.NewAppCreated)
                                {
                                    app.App.Quit();
                                }

                                app = null;
                            }
                        }))
                        {
                            bool WbkOpened;
                            var  wbk = WorkbookGenerator.OpenWbk(excelApp, SelectedComp.SourceWorkbookName, out WbkOpened);

                            if (wbk != null)
                            {
                                foreach (MSExcel.Worksheet wsh in wbk.Worksheets)
                                {
                                    SheetNames.Add(wsh.Name);
                                }
                            }
                            else
                            {
                                MessageBox.Show(this,
                                                string.Format(Properties.Resources.resfmtSourceWorkbookCouldNotBeOpened, SelectedComp.SourceWorkbookName),
                                                Title,
                                                MessageBoxButton.OK,
                                                MessageBoxImage.Error);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this,
                                        string.Format(Properties.Resources.resfmtErrorDurExcelOperation, ex.Message),
                                        Title,
                                        MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show(this, Properties.Resources.resInvalidSourceWorkbookName, Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #6
0
        public bool InitWndControls()
        {
            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                               Properties.Resources.resFillingGenerationFromOnlineBDWnd,
                                                                                               this,
                                                                                               CheckAccess()),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                EndYears.Clear();
                StartYears.Clear();
                EndYears.Add((int)enEndYearSpecVals.AndYounger);
                EndYears.Add((int)enEndYearSpecVals.AndElder);
                for (int i = DateTime.Now.Year - 7; i > DateTime.Now.Year - 100; i--)
                {
                    StartYears.Add(i);
                    EndYears.Add(i);
                }


                GroupNames.Clear();
                lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                {
                    foreach (var groupNameDesc in DBManagerApp.m_AppSettings.m_Settings.AvailableGroupNames)
                    {
                        GroupNames.Add(groupNameDesc.GroupName);
                    }
                }

                // Заполняем выпадающие списки текущими значениями
                LocalDBComps.Clear();

                try
                {
                    foreach (var comp in DBManagerApp.m_Entities.descriptions.ToList())
                    {
                        var item = new CompDescLocalWorkbook()
                        {
                            ID        = comp.id_desc,
                            Name      = comp.name,
                            StartDate = DateTime.Today,
                            EndDate   = DateTime.Today.AddDays(2)
                        };
                        item.DestCompFolder   = GetDefaultDestCompFolderName(item);
                        item.PropertyChanged += comp_PropertyChanged;

                        LocalDBComps.Add(item);
                    }
                    SelectedComp = LocalDBComps.LastOrDefault();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this,
                                    string.Format(Properties.Resources.resfmtErrorDuringReadingDataFromOnlineDB, ex.Message),
                                    Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return(false);
                }

                cmbMainJudge.Items.Clear();
                foreach (var mainJudge in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_judge)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainJudge.Items.Add(mainJudge);
                }

                cmbMainSecretary.Items.Clear();
                foreach (var mainSecretary in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_secretary)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainSecretary.Items.Add(mainSecretary);
                }

                cmbRow6.Items.Clear();
                foreach (var row6 in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.row6)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbRow6.Items.Add(row6);
                }
            }

            return(true);
        }
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            dpMain.IsEnabled = false;

            bool HasSelectedTab = false;

            foreach (TabItem ti in tbctrlTabs.Items)
            {
                if (!(ti.Content as CExportingTabBase).CheckSettings())
                {
                    ti.IsSelected    = true;
                    dpMain.IsEnabled = true;
                    return;
                }
                HasSelectedTab |= (ti.Content as CExportingTabBase).CreateReport;
            }

            if (!HasSelectedTab)
            {   // Ничего не выбрано
                MessageBox.Show(this,
                                Properties.Resources.resNoTaskToExport,
                                Title,
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                dpMain.IsEnabled = true;
                return;
            }

            if (MainExportTab.CreateReport)
            {
                if (string.IsNullOrWhiteSpace(txtXlsPath.Text) ||
                    !Directory.Exists(System.IO.Path.GetDirectoryName(txtXlsPath.Text)) ||
                    System.IO.Path.GetExtension(txtXlsPath.Text) != GlobalDefines.XLSX_EXTENSION)
                {
                    MessageBox.Show(this,
                                    Properties.Resources.resInvalidXlsxPath,
                                    Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    dpMain.IsEnabled = true;
                    return;
                }

                if (File.Exists(txtXlsPath.Text))
                {       // Перезаписывать файлы нельзя
                    MessageBox.Show(this,
                                    Properties.Resources.resXlsxFileAlreadyExists,
                                    Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    dpMain.IsEnabled = true;
                    return;
                }
            }

            if (TeamExportTab.HasLeadReport && LeadReportInfoTab.Groups.FirstOrDefault(arg => arg.LeadSheetIndex < 0) != null)
            {   // Для командного отчёта нужно присвоить листы всем группам в трудности
                MessageBox.Show(this,
                                Properties.Resources.resGroupWithoutLeadSheetIndex,
                                Properties.Resources.resError,
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                (TeamExportTab.Parent as TabItem).IsSelected = true;
                dpMain.IsEnabled = true;
                return;
            }

            foreach (TabItem ti in tbctrlTabs.Items)
            {
                (ti.Content as CExportingTabBase).BeforeExporting();
            }

            AutoResetEvent hFinishedSearchEvent = null;
            Thread         th = null;

            if ((DBManagerApp.MainWnd as DispatcherObject).CheckAccess())
            {
                CWaitingWnd.ShowAsync(out hFinishedSearchEvent,
                                      out th,
                                      Title,
                                      string.Format(Properties.Resources.resfmtExportingToExcel, txtXlsPath.Text),
                                      this);
            }

            MSExcel.Application excelApp = GlobalDefines.StartExcel(out bool NewAppCreated);

            if (excelApp != null)
            {
                excelApp.DisplayAlerts = false; // Отключаем различные сообщения

                MSExcel.Workbook wbkTarget          = null;
                MSExcel.Workbook wbkTemplates       = null;
                bool             WbkTemplatesOpened = false;

                string WbkTargetPath = txtXlsPath.Text;

                try
                {
                    if (MainExportTab.CreateReport)
                    {
                        // Создаём книгу, в которую будем добавлять листы
                        wbkTarget = excelApp.Workbooks.Add(MSExcel.XlWBATemplate.xlWBATWorksheet);
                        if (wbkTarget == null)
                        {
                            MessageBox.Show(this,
                                            string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                          Properties.Resources.resCantCreateTargetWbk),
                                            Title,
                                            MessageBoxButton.OK,
                                            MessageBoxImage.Error);
                            throw new NotImplementedException();
                        }

                        // Открываем книгу с шаблонами
                        wbkTemplates = OpenWbkTemplates(excelApp, NewAppCreated, out WbkTemplatesOpened);
                        if (wbkTemplates == null)
                        {
                            throw new NotImplementedException();
                        }

                        CReportExporterBase.CTask Task = null;
                        foreach (CGroupItem GroupItem in MainExportTab.SelectedGroups)
                        {
                            foreach (CRoundItem RoundItem in GroupItem.Rounds.Where(arg => arg.IsSelected))
                            {
                                switch ((enReportTypes)RoundItem.id)
                                {
                                case enReportTypes.Qualif:
                                case enReportTypes.Qualif2:
                                    Task = new CQualifExporter.CQualifTask()
                                    {
                                        m_ReportType    = (enReportTypes)RoundItem.id,
                                        m_CompDesc      = this.m_CompDesc,
                                        m_GroupToExport = GroupItem
                                    };
                                    break;

                                case enReportTypes.OneEighthFinal:
                                case enReportTypes.QuaterFinal:
                                case enReportTypes.SemiFinal:
                                    Task = new CMiddleSheetsExporter.CMiddleSheetsTask()
                                    {
                                        m_ReportType    = (enReportTypes)RoundItem.id,
                                        m_CompDesc      = this.m_CompDesc,
                                        m_GroupToExport = GroupItem
                                    };
                                    break;

                                case enReportTypes.Final:
                                    Task = new CFinalExporter.CFinalTask()
                                    {
                                        m_ReportType    = (enReportTypes)RoundItem.id,
                                        m_CompDesc      = this.m_CompDesc,
                                        m_GroupToExport = GroupItem
                                    };
                                    break;

                                case enReportTypes.Total:
                                    Task = new CTotalExporter.CTotalTask()
                                    {
                                        m_ReportType    = (enReportTypes)RoundItem.id,
                                        m_CompDesc      = this.m_CompDesc,
                                        m_GroupToExport = GroupItem
                                    };
                                    break;
                                }

                                CReportExporterBase ReportExporter = CReportExporterBase.GetReportClass(Task);
                                if (ReportExporter == null ||
                                    !ReportExporter.CreateReport(excelApp, wbkTarget, wbkTemplates))
                                {
                                    MessageBox.Show(this,
                                                    string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                                  string.Format(Properties.Resources.resfmtErrDurQualifExporting,
                                                                                GroupItem.Name,
                                                                                RoundItem.RoundName)),
                                                    Title,
                                                    MessageBoxButton.OK,
                                                    MessageBoxImage.Error);
                                }
                            }
                        }
                    }

                    if (TeamExportTab.CreateReport)
                    {
                        if (!TeamExportTab.HasLeadReport || LeadReportInfoTab.HasLeadReport)
                        {
                            bool WbkLeadReportOpened = false;
                            bool CreateNewWbk        = false;
                            if (wbkTarget == null)
                            {   // Книга не была ранее создана
                                CreateNewWbk = true;
                                if (TeamExportTab.ExportToAnotherWbk)
                                {
                                    WbkTargetPath = TeamExportTab.XlsPath;
                                }
                            }
                            else if (TeamExportTab.ExportToAnotherWbk)
                            {   // Сохраняем текущую книгу, т.к. двоеборье нужно добавлять в новую
                                CreateNewWbk = true;
                                if (wbkTarget.Worksheets.Count > 1)
                                {       // Удалось добавить хотя бы 1 лист
                                    // Удаляем первый лист, который был создан автоматически при создании книги
                                    wbkTarget.Worksheets[1].Delete();
                                    wbkTarget.SaveAs(WbkTargetPath);
                                    if (!ShowWbkAfterExport)
                                    {
                                        wbkTarget.Close();
                                    }
                                }
                                else
                                {
                                    wbkTarget.Close();
                                    File.Delete(WbkTargetPath);
                                }
                                WbkTargetPath = TeamExportTab.XlsPath;

                                wbkTarget = null;
                            }

                            // Создаём книгу, в которую будем добавлять листы
                            if (CreateNewWbk)
                            {
                                wbkTarget = excelApp.Workbooks.Add(MSExcel.XlWBATemplate.xlWBATWorksheet);
                                if (wbkTarget == null)
                                {
                                    MessageBox.Show(this,
                                                    string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                                  Properties.Resources.resCantCreateTargetWbk),
                                                    Title,
                                                    MessageBoxButton.OK,
                                                    MessageBoxImage.Error);
                                    throw new NotImplementedException();
                                }
                            }

                            if (wbkTemplates == null)
                            {   // Открываем книгу с шаблонами
                                wbkTemplates = OpenWbkTemplates(excelApp, NewAppCreated, out WbkTemplatesOpened);
                                if (wbkTemplates == null)
                                {
                                    throw new NotImplementedException();
                                }
                            }

                            CTeamExporter.CTeamTask Task = new CTeamExporter.CTeamTask()
                            {
                                m_ReportType = enReportTypes.Team,
                                m_CompDesc   = this.m_CompDesc,

                                m_Teams        = TeamExportTab.TeamsForReport.ToList(),
                                m_MenInGroup   = TeamExportTab.MenInGroup,
                                m_WomenInGroup = TeamExportTab.WomenInGroup,
                            };
                            if (TeamExportTab.HasLeadReport)
                            {
                                Task.m_LeadReportInfo.m_wbkLeadReport           = OpenWbkLeadReport(excelApp, NewAppCreated, LeadReportInfoTab.XlsPath, out WbkLeadReportOpened);
                                Task.m_LeadReportInfo.m_dictLeadGroupInfos      = LeadReportInfoTab.Groups.ToDictionary(arg => arg.id);
                                Task.m_LeadReportInfo.m_LeadSheets              = LeadReportInfoTab.LeadSheets.ToList();
                                Task.m_LeadReportInfo.m_FirstMemberRow          = LeadReportInfoTab.FirstMemberRow;
                                Task.m_LeadReportInfo.m_PersonalDataColumnIndex = LeadReportInfoTab.PersonalDataColumnIndex;
                                Task.m_LeadReportInfo.m_PlaceColumnIndex        = LeadReportInfoTab.PlaceColumnIndex;
                                Task.m_LeadReportInfo.m_YearOfBirthColumnIndex  = LeadReportInfoTab.YearOfBirthColumnIndex;
                                Task.m_LeadReportInfo.m_TeamColumnIndex         = LeadReportInfoTab.TeamColumnIndex;
                            }

                            CReportExporterBase ReportExporter = CReportExporterBase.GetReportClass(Task);
                            if (ReportExporter == null ||
                                !ReportExporter.CreateReport(excelApp, wbkTarget, wbkTemplates))
                            {
                                MessageBox.Show(this,
                                                string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                              Properties.Resources.resErrDurTeamExporting),
                                                Title,
                                                MessageBoxButton.OK,
                                                MessageBoxImage.Error);
                            }

                            if (Task.m_LeadReportInfo.m_wbkLeadReport != null && WbkLeadReportOpened)
                            {   // Закрываем открытую ранее книгу с отчётом трудности
                                Task.m_LeadReportInfo.m_wbkLeadReport.Close();
                            }
                        }
                        else
                        {       // Не выбран протокол трудности
                            MessageBox.Show(this,
                                            string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                          Properties.Resources.resNoLeadReport),
                                            Title,
                                            MessageBoxButton.OK,
                                            MessageBoxImage.Error);
                        }
                    }

                    if (PersonalExportTab.CreateReport)
                    {
                        if (!PersonalExportTab.HasLeadReport || LeadReportInfoTab.HasLeadReport)
                        {
                            bool WbkLeadReportOpened = false;
                            bool CreateNewWbk        = false;
                            if (wbkTarget == null)
                            {   // Книга не была ранее создана
                                CreateNewWbk = true;
                                if (PersonalExportTab.ExportToAnotherWbk)
                                {
                                    WbkTargetPath = PersonalExportTab.XlsPath;
                                }
                            }
                            else if (PersonalExportTab.ExportToAnotherWbk)
                            {   // Сохраняем текущую книгу, т.к. двоеборье нужно добавлять в новую
                                CreateNewWbk = true;
                                if (wbkTarget.Worksheets.Count > 1)
                                {       // Удалось добавить хотя бы 1 лист
                                    // Удаляем первый лист, который был создан автоматически при создании книги
                                    wbkTarget.Worksheets[1].Delete();
                                    wbkTarget.SaveAs(WbkTargetPath);
                                    if (!ShowWbkAfterExport)
                                    {
                                        wbkTarget.Close();
                                    }
                                }
                                else
                                {
                                    wbkTarget.Close();
                                    File.Delete(WbkTargetPath);
                                }
                                WbkTargetPath = PersonalExportTab.XlsPath;

                                wbkTarget = null;
                            }

                            // Создаём книгу, в которую будем добавлять листы
                            if (CreateNewWbk)
                            {
                                wbkTarget = excelApp.Workbooks.Add(MSExcel.XlWBATemplate.xlWBATWorksheet);
                                if (wbkTarget == null)
                                {
                                    MessageBox.Show(this,
                                                    string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                                  Properties.Resources.resCantCreateTargetWbk),
                                                    Title,
                                                    MessageBoxButton.OK,
                                                    MessageBoxImage.Error);
                                    throw new NotImplementedException();
                                }
                            }

                            if (wbkTemplates == null)
                            {   // Открываем книгу с шаблонами
                                wbkTemplates = OpenWbkTemplates(excelApp, NewAppCreated, out WbkTemplatesOpened);
                                if (wbkTemplates == null)
                                {
                                    throw new NotImplementedException();
                                }
                            }

                            CPersonalExporter.CPersonalTask Task = new CPersonalExporter.CPersonalTask()
                            {
                                m_ReportType = enReportTypes.Personal,
                                m_CompDesc   = this.m_CompDesc,

                                m_Groups = PersonalExportTab.SelectedGroups,
                                m_PlaceAggregationMethod  = PersonalExportTab.PlaceAggregationMethod,
                                m_WinnerDetection         = PersonalExportTab.WinnerDetection,
                                m_PriorityCompetitionKind = PersonalExportTab.PriorityCompetitionKind
                            };
                            if (PersonalExportTab.HasLeadReport)
                            {
                                Task.m_LeadReportInfo.m_wbkLeadReport           = OpenWbkLeadReport(excelApp, NewAppCreated, LeadReportInfoTab.XlsPath, out WbkLeadReportOpened);
                                Task.m_LeadReportInfo.m_dictLeadGroupInfos      = LeadReportInfoTab.Groups.ToDictionary(arg => arg.id);
                                Task.m_LeadReportInfo.m_LeadSheets              = LeadReportInfoTab.LeadSheets.ToList();
                                Task.m_LeadReportInfo.m_FirstMemberRow          = LeadReportInfoTab.FirstMemberRow;
                                Task.m_LeadReportInfo.m_PersonalDataColumnIndex = LeadReportInfoTab.PersonalDataColumnIndex;
                                Task.m_LeadReportInfo.m_PlaceColumnIndex        = LeadReportInfoTab.PlaceColumnIndex;
                                Task.m_LeadReportInfo.m_YearOfBirthColumnIndex  = LeadReportInfoTab.YearOfBirthColumnIndex;
                                Task.m_LeadReportInfo.m_TeamColumnIndex         = LeadReportInfoTab.TeamColumnIndex;
                            }

                            CReportExporterBase ReportExporter = CReportExporterBase.GetReportClass(Task);
                            if (ReportExporter == null ||
                                !ReportExporter.CreateReport(excelApp, wbkTarget, wbkTemplates))
                            {
                                MessageBox.Show(this,
                                                string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                              Properties.Resources.resErrDurPersonalExporting),
                                                Title,
                                                MessageBoxButton.OK,
                                                MessageBoxImage.Error);
                            }

                            if (Task.m_LeadReportInfo.m_wbkLeadReport != null && WbkLeadReportOpened)
                            {   // Закрываем открытую ранее книгу с отчётом трудности
                                Task.m_LeadReportInfo.m_wbkLeadReport.Close();
                            }
                        }
                        else
                        {       // Не выбран протокол трудности
                            MessageBox.Show(this,
                                            string.Format(Properties.Resources.resfmtErrorDurExcelOperation,
                                                          Properties.Resources.resNoLeadReport),
                                            Title,
                                            MessageBoxButton.OK,
                                            MessageBoxImage.Error);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (!(ex is NotImplementedException))
                    {
                        MessageBox.Show(this,
                                        string.Format(Properties.Resources.resfmtErrorDurExcelOperation, ex.Message),
                                        Title,
                                        MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                    }
                }

                if (wbkTarget != null)
                {
                    if (wbkTarget.Worksheets.Count > 1)
                    {   // Удалось добавить хотя бы 1 лист
                        // Удаляем первый лист, который был создан автоматически при создании книги
                        // Перед этим обязательно нужно показать книгу, т.к. без этого метод Delete падает
                        excelApp.Visible     = true;
                        excelApp.WindowState = MSExcel.XlWindowState.xlMinimized;
                        excelApp.WindowState = MSExcel.XlWindowState.xlNormal;
                        excelApp.WindowState = MSExcel.XlWindowState.xlMinimized;
                        wbkTarget.Worksheets[1].Delete();
                        wbkTarget.SaveAs(WbkTargetPath);

                        if (ShowWbkAfterExport)
                        {
                            NewAppCreated = false;
                            wbkTarget.Activate();
                        }
                        else
                        {
                            excelApp.Visible = false;
                            wbkTarget.Close();
                        }
                    }
                    else
                    {
                        wbkTarget.Close();
                        File.Delete(WbkTargetPath);
                    }
                }

                if (wbkTemplates != null && WbkTemplatesOpened)
                {
                    wbkTemplates.Close();
                }
                wbkTemplates = null;

                excelApp.DisplayAlerts = true;

                if (NewAppCreated)
                {
                    excelApp.Quit();
                }

                excelApp = null;
            }
            else
            {
                MessageBox.Show(this,
                                string.Format(Properties.Resources.resfmtErrorDurExcelOperation, Properties.Resources.resCantCreateExcelApp),
                                Title,
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
            }

            if (hFinishedSearchEvent != null)
            {
                hFinishedSearchEvent.Set();
            }

            MessageBox.Show(this,
                            Properties.Resources.resExportToExcelFinished,
                            Title,
                            MessageBoxButton.OK,
                            MessageBoxImage.Information);

            dpMain.IsEnabled = true;
        }
Exemple #8
0
        private void m_PathWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            LastException = null;

            lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                if (!DBManagerApp.m_AppSettings.m_Settings.HandleFileDeletion)
                {
                    return;
                }

            AutoResetEvent hFinishedSearchEvent = null;
            Thread         th = null;

            if ((DBManagerApp.MainWnd as DispatcherObject).CheckAccess())
            {
                CWaitingWnd.ShowAsync(out hFinishedSearchEvent,
                                      out th,
                                      DBManagerApp.MainWnd.Title,
                                      string.Format(Properties.Resources.resfmtHandlingFileDeletion, e.FullPath),
                                      DBManagerApp.MainWnd);
            }

            lock (EventsCS)
            {
                if (State != enScanningThreadState.Worked)
                {
                    return;
                }

                CFileScanner Scanner;
                if (m_FileScanners.TryGetValue(e.FullPath, out Scanner))
                {
                    m_PathWatcher.EnableRaisingEvents = false;

                    if (Scanner.Group != null)
                    {
                        long GroupId = Scanner.Group.id_group;

                        if (Scanner.DeleteGroup()) // DeleteGroup автоматически вызовет Stop
                        {
                            m_FileScanners.Remove(e.FullPath);

                            List <CDataChangedInfo> Changes = new List <CDataChangedInfo>();
                            Changes.Add(new CDataChangedInfo(this)
                            {
                                ChangedObjects = enDataChangedObjects.Paths | enDataChangedObjects.Group,
                                ChangingType   = enDataChangesTypes.Delete,
                                ID             = GroupId,
                                Argument       = e.FullPath,
                                GroupID        = GroupId
                            });
                            RaiseDataChangedEvent(new DataChangedEventArgs(Changes));
                        }
                    }

                    m_PathWatcher.EnableRaisingEvents = true;
                }
            }

            if (hFinishedSearchEvent != null)
            {
                hFinishedSearchEvent.Set();
            }
        }
Exemple #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Param"></param>
        /// <param name="MadeChanges"></param>
        public override bool SyncWithFilesAndDB(CScannerBase.CSyncParamBase Param)
        {
            LastException = null;

            CSyncParam SyncParam = Param as CSyncParam;

            if (SyncParam == null ||
                SyncParam.m_Dir == GlobalDefines.DEFAULT_XML_STRING_VAL ||
                !Directory.Exists(SyncParam.m_Dir))
            {
                return(false);
            }

            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(DBManagerApp.MainWnd.Title,
                                                                                               string.Format(Properties.Resources.resfmtSyncingDir, SyncParam.m_Dir),
                                                                                               DBManagerApp.MainWnd,
                                                                                               true),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                lock (EventsCS)
                {
                    if (State == enScanningThreadState.Worked)
                    {   // Синхронизацию можно проводить только при незапущенном сканировании
                        return(false);
                    }

                    m_PathWatcher.EnableRaisingEvents = false;

                    List <string> ScannedFilesFullPaths = new List <string>();

                    try
                    {
                        if (SyncParam.m_lstFileScannerSettings != null)
                        {
                            bool AllFilesSync = true;

                            foreach (CFileScannerSettings ScannerSettings in SyncParam.m_lstFileScannerSettings)
                            {
                                if (Path.GetDirectoryName(ScannerSettings.FullFilePath) != SyncParam.m_Dir)
                                {   // Файл не находится в просматриваемой папке => он нам не нужен
                                    AllFilesSync = false;
                                    lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                        DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(ScannerSettings.FullFilePath);
                                    continue;
                                }

                                string FullScannerFilePath = Path.Combine(SyncParam.m_Dir, ScannerSettings.FullFilePath);
                                ScannedFilesFullPaths.Add(FullScannerFilePath);

                                CFileScanner Scanner = null;
                                if (m_FileScanners.TryGetValue(FullScannerFilePath, out Scanner))
                                {
                                    m_FileScanners[FullScannerFilePath] =
                                        Scanner = new CFileScanner(ScannerSettings.FullFilePath,
                                                                   this,
                                                                   true,
                                                                   new CFileScanner.CSyncParam(ScannerSettings.GroupId,
                                                                                               FullScannerFilePath));
                                    if (!Scanner.SyncSuccessfully)
                                    {   // Синхронизироваться не удалось
                                        m_FileScanners.Remove(FullScannerFilePath);
                                        AllFilesSync = false;
                                        lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                            DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(ScannerSettings.FullFilePath);
                                    }
                                }
                                else
                                {
                                    Scanner = new CFileScanner(ScannerSettings.FullFilePath,
                                                               this,
                                                               true,
                                                               new CFileScanner.CSyncParam(ScannerSettings.GroupId,
                                                                                           FullScannerFilePath));
                                    if (Scanner.SyncSuccessfully)
                                    {
                                        m_FileScanners.Add(ScannerSettings.FullFilePath, Scanner);
                                    }
                                    else
                                    {   // Синхронизироваться не удалось
                                        AllFilesSync = false;
                                        lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                            DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(ScannerSettings.FullFilePath);
                                    }
                                }
                            }

                            if (!AllFilesSync)
                            {
                                DBManagerApp.m_AppSettings.Write();
                            }
                        }

                        // Пытаемся загрузить данные из всех остальных XML-файлов, имеющихся в папке
                        string[] AllXMLFullFilePaths = Directory.GetFiles(SyncParam.m_Dir, "*.xml");
                        foreach (string FullFilePath in from xmlFileL in AllXMLFullFilePaths
                                 join xmlFileR in ScannedFilesFullPaths on xmlFileL equals xmlFileR into XMLFiles
                                 from scannedFile in XMLFiles.DefaultIfEmpty()
                                 where scannedFile == null
                                 select xmlFileL)
                        {
                            CFileScanner Scanner = null;
                            if (m_FileScanners.TryGetValue(FullFilePath, out Scanner))
                            {
                                m_FileScanners[FullFilePath] =
                                    Scanner = new CFileScanner(FullFilePath,
                                                               this,
                                                               true,
                                                               new CFileScanner.CSyncParam(m_FileScanners[FullFilePath].Group == null ?
                                                                                           GlobalDefines.NO_OUR_COMP_IN_DB :
                                                                                           m_FileScanners[FullFilePath].Group.id_group,
                                                                                           FullFilePath));
                                if (!Scanner.SyncSuccessfully)
                                {   // Синхронизироваться не удалось
                                    m_FileScanners.Remove(FullFilePath);
                                    lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                        DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(FullFilePath);
                                    continue;
                                }
                            }
                            else
                            {
                                Scanner = new CFileScanner(FullFilePath,
                                                           this,
                                                           true,
                                                           new CFileScanner.CSyncParam(GlobalDefines.NO_OUR_COMP_IN_DB,
                                                                                       FullFilePath));

                                if (Scanner.SyncSuccessfully)
                                {   // Удалось синхронизироваться => добавляем сканер в m_FileScanners и в файл настроек
                                    m_FileScanners.Add(FullFilePath, Scanner);
                                }
                            }

                            if (Scanner.Group != null)
                            {
                                CFileScannerSettings ScannerSettings = new CFileScannerSettings()
                                {
                                    FullFilePath = FullFilePath,
                                    GroupId      = Scanner.Group.id_group
                                };
                                lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                    DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.TryAddValue(FullFilePath, ScannerSettings);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        List <CDataChangedInfo> Changes = new List <CDataChangedInfo>();
                        OnException(ref Changes, ex, CompId);
                    }

                    if (Directory.Exists(m_PathWatcher.Path))
                    {
                        m_PathWatcher.EnableRaisingEvents = true;
                    }
                }
            }

            return(true);
        }
        public bool InitWndControls()
        {
            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                               Properties.Resources.resFillingGenerationFromOnlineBDWnd,
                                                                                               this,
                                                                                               CheckAccess()),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                EndYears.Clear();
                StartYears.Clear();
                EndYears.Add((int)enEndYearSpecVals.AndYounger);
                EndYears.Add((int)enEndYearSpecVals.AndElder);
                for (int i = DateTime.Now.Year - 7; i > DateTime.Now.Year - 100; i--)
                {
                    StartYears.Add(i);
                    EndYears.Add(i);
                }

                // Заполняем выпадающие списки текущими значениями
                RemoteDBComps.Clear();
                if (OnlineDBManager.Instance.IsConnectedToRemoteDB)
                {
                    try
                    {
                        var speedGroups = m_DBManager
                                          .Entities
                                          .group
                                          .Where(gr =>
                                                 gr
                                                 .participants
                                                 .SelectMany(part => part.participants_kind)
                                                 .Any(kind => kind.kind_id == (int)enOnlineDBKind.Speed))
                                          .ToList();

                        // Выбираем только соревы на скорость
                        foreach (var comp in speedGroups.SelectMany(gr => gr.events).Distinct().ToList())
                        {
                            var item = new CompItemRemoteDB()
                            {
                                Desc = new CompDescRemoteDB()
                            };
                            (item.Desc as CompDescRemoteDB).ID              = comp.id;
                            (item.Desc as CompDescRemoteDB).Name            = comp.name;
                            (item.Desc as CompDescRemoteDB).RemoteStartDate = comp.date1;
                            (item.Desc as CompDescRemoteDB).RemoteEndDate   = comp.date2;
                            (item.Desc as CompDescRemoteDB).UpdateDatesFromRemoteOnes();

                            foreach (var group in speedGroups.Where(gr => gr.events.Any(ev => ev.id == comp.id)))
                            {
                                if (DBManagerApp.m_AppSettings.m_Settings.AvailableGroupNames.Any(arg => string.Compare(arg.GroupName, group.name, true) == 0))
                                {
                                    var groupItem = new GroupItemRemoteDB((item.Desc as CompDescRemoteDB))
                                    {
                                        ID        = group.id,
                                        Name      = group.name,
                                        Sex       = ((enOnlineSex)(group.sex ? 1 : 0)).ToLocalSexValue(),
                                        StartYear = DateTime.Now.Year - group.year2,
                                        EndYear   = group.year1.HasValue ? DateTime.Now.Year - group.year1 : null,
                                        StartDate = item.Desc.StartDate,
                                        EndDate   = item.Desc.EndDate
                                    };
                                    item.Groups.Add(groupItem);
                                }
                            }

                            RemoteDBComps.Add(item);
                        }
                        SelectedComp = RemoteDBComps.LastOrDefault();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this,
                                        string.Format(Properties.Resources.resfmtErrorDuringReadingDataFromOnlineDB, ex.Message),
                                        Title,
                                        MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                        return(false);
                    }
                }

                cmbMainJudge.Items.Clear();
                foreach (var mainJudge in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_judge)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainJudge.Items.Add(mainJudge);
                }

                cmbMainSecretary.Items.Clear();
                foreach (var mainSecretary in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_secretary)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainSecretary.Items.Add(mainSecretary);
                }

                cmbRow6.Items.Clear();
                foreach (var row6 in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.row6)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbRow6.Items.Add(row6);
                }
            }

            return(true);
        }