Example #1
0
 public void SetupTitle(string title, string details = "")
 {
     Logging.ToLog("MainWindow - Переход на страницу: " + title +
                   (string.IsNullOrEmpty(details) ? string.Empty : " @ " + details));
     TextBlockTitle.Visibility = Visibility.Visible;
     TextBlockTitle.Text       = title;
 }
Example #2
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            string msg = "App - ===== Запуск приложения";

            Logging.ToLog(msg);
            string adminAddress = Services.Config.Instance.MailAdminAddress;

            ClientMail.SendMail(msg, msg, adminAddress);

            DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            if (!Services.Config.Instance.IsConfigReadedSuccessfull)
            {
                ClientMail.SendMail("Ошибка конфигурации", "Не удалось считать файл конфигурации: " +
                                    Services.Config.Instance.ConfigFilePath, adminAddress);
                Logging.ToLog("App - !!! Конфигурация не загружена");
            }

            Logging.CheckAndCleanOldFiles(Services.Config.Instance.MaxLogfilesQuantity);

            MainWindow window = new MainWindow();

            window.Show();
        }
Example #3
0
        public void CloseAllPages(object sender, RoutedEventArgs e)
        {
            Logging.ToLog("MainWindow - закрытие всех страниц");

            try {
                while (FrameMain.NavigationService.CanGoBack)
                {
                    FrameMain.NavigationService.GoBack();
                    FrameMain.NavigationService.RemoveBackEntry();
                }
            } catch (Exception exc) {
                Logging.ToLog(exc.Message + Environment.NewLine + exc.StackTrace);
            }

            if (!(FrameMain.Content is PageRangeSelection))
            {
                FrameMain.NavigationService.Navigate(rootPage);
            }

            if (ItemSurveyResult.Instance.NeedToWriteToDb)
            {
                ItemSurveyResult.WriteSurveyResultToDb();
            }

            autoCloseTimer.Stop();
            GC.Collect();
        }
Example #4
0
        private void AutoCloseTimer_Tick(object sender, EventArgs e)
        {
            infoPageCloseCounter++;

            if (FrameMain.Content is PageServices ||
                FrameMain.Content is PageSchedule)
            {
                if (infoPageCloseCounter < Services.Config.Instance.AutoCloseTImerInfoPageMultiplier)
                {
                    return;
                }
            }

            Logging.ToLog("MainWindow - Автозакрытие страницы по таймеру");

            if (ItemSurveyResult.Instance.NeedToWriteToDb)
            {
                if (FrameMain.Content is PageCallback)
                {
                    ItemSurveyResult.Instance.SetPhoneNumber("Timeout");
                }
                else if (FrameMain.Content is PageComment)
                {
                    ItemSurveyResult.Instance.SetComment("Timeout");
                }

                ItemSurveyResult.WriteSurveyResultToDb();
            }

            CloseAllPages(null, null);
        }
Example #5
0
        private void NavigateBack(object sender, RoutedEventArgs e)
        {
            Logging.ToLog("MainWindow - Возврат на предыдущую страницу");

            if (FrameMain.NavigationService.CanGoBack)
            {
                FrameMain.NavigationService.GoBack();
                FrameMain.NavigationService.RemoveBackEntry();
            }
        }
Example #6
0
        public MainWindow()
        {
            InitializeComponent();

            PreviewKeyDown += (s, e) => {
                if (e.Key.Equals(Key.Escape))
                {
                    Logging.ToLog("MainWindow - ===== Завершение работы по нажатию клавиши ESC");
                    Application.Current.Shutdown();
                }
            };

            StartTimeDelimiterTick();

            FrameMain.JournalOwnership = JournalOwnership.OwnsJournal;

            autoCloseTimer = new DispatcherTimer {
                Interval = TimeSpan.FromSeconds(Services.Config.Instance.AutoCloseTimerIntervalInSeconds)
            };

            autoCloseTimer.Tick += AutoCloseTimer_Tick;
            FrameMain.Navigated += FrameMain_Navigated;
            PreviewMouseDown    += MainWindow_PreviewMouseDown;

            Services.DataProvider.LoadData();

            Loaded += (s, e) => {
                rootPage = new PageSelectSection();
                FrameMain.NavigationService.Navigate(rootPage);
            };

            instance = this;
            StyleButtonRoundedCorner = Application.Current.MainWindow.FindResource("RoundCorner") as Style;

            dateTimeStart = DateTime.Now;
            DispatcherTimer autoQuitTimer = new DispatcherTimer {
                Interval = TimeSpan.FromMinutes(1)
            };

            autoQuitTimer.Tick += (s, e) => {
                if (DateTime.Now.Date != dateTimeStart.Date)
                {
                    Logging.ToLog("MainWindow - ==== Автоматическое завершение работы");
                    Application.Current.Shutdown();
                }
            };
            autoQuitTimer.Start();

            if (Services.Config.Instance.IsDebug)
            {
                Topmost = false;
                Cursor  = Cursors.Arrow;
            }
        }
Example #7
0
        public static async void WriteSurveyResultToDb()
        {
            await Task.Run(() => {
                ItemSurveyResult surveyResult = Instance;
                SendMailAboutNegativeMark(surveyResult);

                if ((DateTime.Now - previousRateTime).TotalSeconds >= 120)
                {
                    previousRatesDcodes.Clear();
                }

                string mark = surveyResult.Mark;
                if (previousRatesDcodes.Contains(surveyResult.DCode))
                {
                    mark = "Duplicate";
                }
                else
                {
                    previousRatesDcodes.Add(surveyResult.DCode);
                }

                Logging.ToLog("ItemSurveyResult - Запись результата опроса в базу данных: " + surveyResult.ToString());

                using (Services.FirebirdClient fBClient = new Services.FirebirdClient(
                           Services.Config.Instance.MisDbAddress,
                           Services.Config.Instance.MisDbPort,
                           Services.Config.Instance.MisDbName,
                           Services.Config.Instance.MisDbUserName,
                           Services.Config.Instance.MisDbUserPassword)) {
                    Dictionary <string, object> surveyResults = new Dictionary <string, object>()
                    {
                        { "@dcode", surveyResult.DCode },
                        { "@docrate", mark },
                        { "@comment", surveyResult.Comment },
                        { "@phonenumber", surveyResult.PhoneNumber },
                        { "@photopath", surveyResult.PhotoLink },
                        { "@depnum", surveyResult.DocDeptCode }
                    };

                    string query = Services.Config.Instance.SqlInsertLoyaltySurveyResult;
                    Logging.ToLog("ItemSurveyResult - Результат выполнения: " + fBClient.ExecuteUpdateQuery(query, surveyResults));

                    previousRateTime = surveyResult.SurveyDateTime.Value;
                }
            }).ConfigureAwait(false);
        }
Example #8
0
        private void HandleException(Exception exception)
        {
            if (exception != null)
            {
                string msg = exception.Message + Environment.NewLine + exception.StackTrace;
                Logging.ToLog("App - " + msg);
                ClientMail.SendMail("Необработанное исключение", msg, Services.Config.Instance.MailAdminAddress);
            }

            if (exception.InnerException != null)
            {
                Logging.ToLog("App - " + exception.InnerException.Message + Environment.NewLine + exception.InnerException.StackTrace);
            }

            Logging.ToLog("App - !!! Аварийное завершение работы");
            Process.GetCurrentProcess().Kill();
        }
Example #9
0
        public static async void SendMail(string subject, string body, string receiver, string attachmentPath = "")
        {
            Logging.ToLog("Mail - Отправка сообщения, тема: " + subject + ", текст: " + body);
            Logging.ToLog("Mail - Получатели: " + receiver);

            if (string.IsNullOrEmpty(receiver) ||
                !Services.Config.Instance.ShouldSendMail)
            {
                Logging.ToLog("Mail - Пропуск отправки в соответствии с настройками");
                return;
            }

            try {
                SmtpClient client = CreateClientAndMessage(subject, body, receiver, out MailMessage message, attachmentPath);
                await Task.Run(() => { client.Send(message); }).ConfigureAwait(false);

                Logging.ToLog("Mail - Письмо отправлено успешно");
                DisposeResources(client, message);
            } catch (Exception e) {
                Logging.ToLog("Mail - SendMail exception: " + e.Message + Environment.NewLine + e.StackTrace);
            }
        }
Example #10
0
        public static void SendMailAboutNegativeMark(ItemSurveyResult surveyResult)
        {
            if (surveyResult == null)
            {
                return;
            }

            string header = "";

            string recipients = string.Empty;
            string mark;

            switch (surveyResult.Type)
            {
            case SurveyType.Doctor:
                recipients = Services.Config.Instance.MailRecipientsNegativeMarksDoctor;
                break;

            case SurveyType.Registry:
                recipients = Services.Config.Instance.MailRecipientsNegativeMarksRegistry;
                break;

            case SurveyType.Clinic:
                recipients = Services.Config.Instance.MailRecipientsNegativeMarksClinic;
                break;

            default:
                break;
            }

            if (surveyResult.Mark.Equals("0"))
            {
                mark = "Крайне не буду рекомендовать";
            }
            else if (surveyResult.Mark.Equals("1"))
            {
                mark = "Очень плохо";
            }
            else if (surveyResult.Mark.Equals("2"))
            {
                mark = "Плохо";
            }
            else
            {
                return;
            }

            if (surveyResult.PhoneNumber.Length == 10 &&
                !surveyResult.PhoneNumber.Equals("skipped"))
            {
                header = "Пациент указал, что ему можно позвонить для уточнения подробностей " +
                         "о его негативной оценке.";
            }
            else if (!string.IsNullOrEmpty(surveyResult.Comment) &&
                     !string.IsNullOrWhiteSpace(surveyResult.Comment) &&
                     !surveyResult.Comment.Equals("skipped"))
            {
                header = "Пациент оставил комментарий к своей негативной оценке";
            }

            if (string.IsNullOrEmpty(header))
            {
                Logging.ToLog("ItemSurveyResult - Пропуск отправки сообщения об обратной связи - " +
                              "неверный формат номера телефона и отсутствует комментарий");
                return;
            }

            string subject = Services.Config.Instance.MailClinicName + " - обратная связь с пациентом через монитор лояльности";
            string body    =
                header + "<br><br>" +
                "<table border=\"1\">" +
                "<tr><td>Сотрудник</td><td><b>" + surveyResult.DocName + "</b></td></tr>" +
                "<tr><td>Отделение</td><td><b>" + surveyResult.DocDepartment + "</b></td></tr>" +
                "<tr><td>Оценка</td><td><b>" + mark + "</b></td></tr>" +
                "<tr><td>Комментарий</td><td><b>" +
                (surveyResult.Comment.Equals("skipped") ? "отказался" : surveyResult.Comment) + "</b></td></tr>" +
                "<tr><td>Номер телефона для связи</td><td><b>" +
                (surveyResult.PhoneNumber.Equals("skipped") ? "отказался" : surveyResult.PhoneNumber) + "</b></td></tr>" +
                "</table><br>";

            string attachmentPath = surveyResult.PhotoLink;

            if (File.Exists(attachmentPath))
            {
                body += "Фотография с камеры терминала:";
            }
            else
            {
                body += "Фотография отсутствует";
            }
            body += "</b>";

            ClientMail.SendMail(subject, body, recipients, attachmentPath);
        }
Example #11
0
 private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     Logging.ToLog("App - !!! App_DispatcherUnhandledException: " + e.ToString());
     HandleException(e.Exception);
 }
Example #12
0
 private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     Logging.ToLog("App - !!! CurrentDomain_UnhandledException: " + e.ExceptionObject.ToString());
     HandleException(e.ExceptionObject as Exception);
 }
        public PageSelectDepartment(Source source)
        {
            InitializeComponent();
            MainWindow.Instance.SetupPage(this, ButtonBack, ButtonHome);
            this.source = source;

            switch (source)
            {
            case Source.Price:
                title    = "Услуги и цены";
                subtitle = "Выберите отделение, для которого Вы хотите увидеть список услуг";
                TextBlockInsideSearchButton.Text = "Поиск по названию услуги";
                ButtonBack.Visibility            = Visibility.Hidden;
                break;

            case Source.DocInfo:
                title    = "Врачи";
                subtitle = "Выберите отделение, для которого Вы хотите увидеть список врачей";
                break;

            case Source.Timetable:
                title    = "Расписание приёма врачей";
                subtitle = "Выберите отделение, для которого Вы хотите увидеть расписание";
                ButtonBack.Visibility = Visibility.Hidden;
                break;

            case Source.DocRate:
                title    = "Оценка приёма у врача";
                subtitle = "Выберите отделение, в котором Вы были на приёме";
                break;

            default:
                title    = string.Empty;
                subtitle = string.Empty;
                break;
            }

            UserContent.JournalOwnership = JournalOwnership.OwnsJournal;
            Loaded += (s, e) => {
                (Application.Current.MainWindow as MainWindow).SetupTitle(title);

                if (!isLoaded)
                {
                    List <string> departments = new List <string>();

                    if (source == Source.Price)
                    {
                        try {
                            departments = Services.DataProvider.Services.Keys.ToList();
                        } catch (Exception exc) {
                            Logging.ToLog(exc.Message + Environment.NewLine + exc.StackTrace);
                        }
                    }

                    else if (source == Source.Timetable)
                    {
                        try {
                            departments = Services.DataProvider.Schedule.Keys.ToList();
                        } catch (Exception exc) {
                            Logging.ToLog(exc.Message + Environment.NewLine + exc.StackTrace);
                        }
                    }

                    else if (source == Source.DocRate)
                    {
                        try {
                            foreach (KeyValuePair <string, List <ItemDoctor> > item in Services.DataProvider.Survey)
                            {
                                if (item.Value.Count > 0)
                                {
                                    departments.Add(item.Key);
                                }
                            }
                        } catch (Exception exc) {
                            Logging.ToLog(exc.Message + Environment.NewLine + exc.StackTrace);
                        }
                    }

                    List <string> pageObjects = new List <string>();
                    try {
                        for (int i = 0; i < departments.Count; i++)
                        {
                            pageObjects.Add(departments[i]);

                            if (pageObjects.Count == 24)
                            {
                                AddPageToList(pageObjects);
                            }
                        }

                        if (pageObjects.Count > 0)
                        {
                            AddPageToList(pageObjects);
                        }
                    } catch (Exception exc) {
                        Logging.ToLog(exc.Message + Environment.NewLine + exc.StackTrace);
                    }

                    if (pages.Count > 0)
                    {
                        UserContent.Content = pages[0].Key;
                    }
                    else
                    {
                        UserContent.Visibility     = Visibility.Hidden;
                        TextBlockNoData.Visibility = Visibility.Visible;
                        return;
                    }

                    isLoaded = true;

                    if (pages.Count > 1)
                    {
                        ButtonScrollDown.Click   += ButtonScrollDown_Click;
                        ButtonScrollUp.Click     += ButtonScrollUp_Click;
                        pages[0].Value.Background = new SolidColorBrush(Colors.Gray);

                        ButtonScrollDown.Visibility   = Visibility.Visible;
                        GridPagesIndicator.Visibility = Visibility.Visible;
                    }

                    currentPageIndex = 0;
                }
            };

            MainWindow.ApplyStyleForButtons(new List <Button> {
                ButtonSearch, ButtonScrollUp, ButtonScrollDown
            });

            TextBlockSubtitle.Text     = subtitle;
            TextBlockSubtitle.FontSize = 40;
        }
Example #14
0
        private static SmtpClient CreateClientAndMessage(string subject, string body, string receiver, out MailMessage message, string attachmentPath = "")
        {
            string appName = Assembly.GetExecutingAssembly().GetName().Name;

            MailAddress        from            = new MailAddress(Services.Config.Instance.MailUser, appName);
            List <MailAddress> mailAddressesTo = new List <MailAddress>();

            if (receiver.Contains(" | "))
            {
                string[] receivers = Services.Config.GetSplittedAddresses(receiver);
                foreach (string address in receivers)
                {
                    try {
                        mailAddressesTo.Add(new MailAddress(address));
                    } catch (Exception e) {
                        Logging.ToLog("Mail - Не удалось разобрать адрес: " + address + Environment.NewLine + e.Message);
                    }
                }
            }
            else
            {
                try {
                    mailAddressesTo.Add(new MailAddress(receiver));
                } catch (Exception e) {
                    Logging.ToLog("Mail - Не удалось разобрать адрес: " + receiver + Environment.NewLine + e.Message);
                }
            }

            body += Environment.NewLine + Environment.NewLine +
                    "___________________________________________" + Environment.NewLine +
                    "Это автоматически сгенерированное сообщение" + Environment.NewLine +
                    "Просьба не отвечать на него" + Environment.NewLine +
                    "Имя системы: " + Environment.MachineName;

            message = new MailMessage();

            foreach (MailAddress mailAddress in mailAddressesTo)
            {
                message.To.Add(mailAddress);
            }

            message.IsBodyHtml = body.Contains("<") && body.Contains(">");

            if (message.IsBodyHtml)
            {
                body = body.Replace(Environment.NewLine, "<br>");
            }

            if (!string.IsNullOrEmpty(attachmentPath) && File.Exists(attachmentPath))
            {
#pragma warning disable IDE0068 // Use recommended dispose pattern
#pragma warning disable CA2000  // Dispose objects before losing scope
                Attachment attachment = new Attachment(attachmentPath);
#pragma warning restore CA2000  // Dispose objects before losing scope
#pragma warning restore IDE0068 // Use recommended dispose pattern

                if (message.IsBodyHtml && attachmentPath.EndsWith(".jpg"))
                {
                    attachment.ContentDisposition.Inline = true;

                    LinkedResource inline = new LinkedResource(attachmentPath, MediaTypeNames.Image.Jpeg)
                    {
                        ContentId = Guid.NewGuid().ToString()
                    };

                    body = body.Replace("Фотография с камеры терминала:", "Фотография с камеры терминала:<br>" +
                                        string.Format(@"<img src=""cid:{0}"" />", inline.ContentId));

                    AlternateView avHtml = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
                    avHtml.LinkedResources.Add(inline);

                    message.AlternateViews.Add(avHtml);
                }
                else
                {
                    message.Attachments.Add(attachment);
                }
            }

            message.From    = from;
            message.Subject = subject;
            message.Body    = body;

            if (Services.Config.Instance.ShouldAddAdminToCopy)
            {
                string adminAddress = Services.Config.Instance.MailAdminAddress;
                if (!string.IsNullOrEmpty(adminAddress))
                {
                    if (adminAddress.Contains(" | "))
                    {
                        string[] adminAddresses = Services.Config.GetSplittedAddresses(adminAddress);
                        foreach (string address in adminAddresses)
                        {
                            try {
                                message.CC.Add(new MailAddress(address));
                            } catch (Exception e) {
                                Logging.ToLog("Mail - Не удалось разобрать адрес: " + address + Environment.NewLine + e.Message);
                            }
                        }
                    }
                    else
                    {
                        try {
                            message.CC.Add(new MailAddress(adminAddress));
                        } catch (Exception e) {
                            Logging.ToLog("Mail - Не удалось разобрать адрес: " + adminAddress + Environment.NewLine + e.Message);
                        }
                    }
                }
            }

            SmtpClient client = new SmtpClient(Services.Config.Instance.MailSmtpServer, (int)Services.Config.Instance.MailSmtpPort)
            {
                UseDefaultCredentials = false,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                EnableSsl             = Services.Config.Instance.MailEnableSSL,
                Credentials           = new System.Net.NetworkCredential(
                    Services.Config.Instance.MailUser,
                    Services.Config.Instance.MailPassword)
            };

            if (!string.IsNullOrEmpty(Services.Config.Instance.MailUserDomain))
            {
                client.Credentials = new System.Net.NetworkCredential(
                    Services.Config.Instance.MailUser,
                    Services.Config.Instance.MailPassword,
                    Services.Config.Instance.MailUserDomain);
            }

            return(client);
        }