//removes a patient from the db and refreshes ItemsSource of the DataGrid
        private async void btnDeletePatient_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("Вы уверены, что хотите удалить карту пациента и все его обращения?", "Внимание!",
                                         MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                var currentCard = dgPatients.SelectedItem as PatientCard;
                if (currentCard != null)
                {
                    Int32 id = currentCard.Id;
                    ClinicDataRepository clinicRepo = new ClinicDataRepository();
                    try
                    {
                        clinicRepo.DeleteCard(id);
                        dgPatients.ItemsSource = await clinicRepo.GetPatientCards();
                    }
                    catch (SqlException)
                    {
                        var err = ConfigurationSettings.AppSettings["dbError"].ToString();
                        MessageBox.Show(err, "Ошибка");
                        throw;
                    }
                    catch
                    {
                        MessageBox.Show("Что то пошло не так, приложение будет закрыто", "Ошибка");
                        throw;
                    }
                }
            }
        }
        //removes a patient request from the db and refreshes ItemsSource of the DataGrid
        private async void btnDeleteRequest_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("Вы уверены, что хотите удалить данное обращение?", "Внимание!",
                                         MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                var currentRequest = dgRequests.SelectedItem as Request;
                if (currentRequest != null)
                {
                    try
                    {
                        ClinicDataRepository clinicRepo = new ClinicDataRepository();
                        clinicRepo.DeleteRequest(currentRequest.RequestId);
                        dgRequests.ItemsSource = await clinicRepo.GetPatientRequests(currentRequest.Patient.Id);
                    }
                    catch (SqlException)
                    {
                        var err = ConfigurationSettings.AppSettings["dbError"].ToString();
                        MessageBox.Show(err, "Ошибка");
                        throw;
                    }
                    catch
                    {
                        MessageBox.Show("Что то пошло не так, приложение будет закрыто", "Ошибка");
                        throw;
                    }
                }
            }
        }
        //gets all requests from the current patient and loads it to dgRequests.ItemSource
        private async void btnPatientRequests_Click(object sender, RoutedEventArgs e)
        {
            var currentCard = dgPatients.SelectedItem as PatientCard;

            if (currentCard != null)
            {
                //in order to see the requests we are switching DataGrids here
                ToggleGridViews();
                ClinicDataRepository clinicRepo = new ClinicDataRepository();
                try
                {
                    dgRequests.ItemsSource = await clinicRepo.GetPatientRequests(currentCard.Id);

                    lblPatientName.Content = currentCard.Name;
                }
                catch (SqlException)
                {
                    var err = ConfigurationSettings.AppSettings["dbError"].ToString();
                    MessageBox.Show(err, "Ошибка");
                    throw;
                }
                catch
                {
                    MessageBox.Show("Что то пошло не так, приложение будет закрыто", "Ошибка");
                    throw;
                }
            }
        }
        //loads DataGrids asynchronously.
        private async void InitializeDataGrids()
        {
            //the cts is cancelling async animation task after we are done here
            CancellationTokenSource cts = new CancellationTokenSource();

            if (isInitializingFirstTime)
            {
                dgPatients.Visibility = Visibility.Collapsed;
                lblLoading.Visibility = Visibility.Visible;
            }
            try
            {
                Animation(cts.Token);
                ClinicDataRepository clinicRepo = new ClinicDataRepository();
                dgPatients.ItemsSource = await clinicRepo.GetPatientCards();

                //after adding a new request or after modifying one,
                //we should refresh the DataGrid to see the changes
                if (tempCard != null)
                {
                    dgRequests.ItemsSource = await clinicRepo.GetPatientRequests(tempCard.Id);
                }
            }
            catch (SqlException)
            {
                var err = ConfigurationSettings.AppSettings["dbError"].ToString();
                MessageBox.Show(err, "Ошибка");
                throw;
            }
            catch
            {
                MessageBox.Show("Что то пошло не так, приложение будет закрыто", "Ошибка");
                throw;
            }

            if (isInitializingFirstTime)
            {
                cts.Cancel();
                lblLoading.Content    = "";
                lblLoading.Visibility = Visibility.Collapsed;
                dgPatients.Visibility = Visibility.Visible;
                //don't invoke the loading loop next time
                isInitializingFirstTime = false;
            }
        }
        //Searching patient card by it's name
        private async void txtBoxSearch_KeyUp(object sender, KeyEventArgs e)
        {
            var txtBox = sender as TextBox;
            ClinicDataRepository clinicRepo = new ClinicDataRepository();

            try
            {
                dgPatients.ItemsSource = await clinicRepo.GetPatientCardsByName(txtBox.Text);
            }
            catch (SqlException)
            {
                var err = ConfigurationSettings.AppSettings["dbError"].ToString();
                MessageBox.Show(err, "Ошибка");
                throw;
            }
            catch
            {
                MessageBox.Show("Что то пошло не так, приложение будет закрыто", "Ошибка");
                throw;
            }
        }
Beispiel #6
0
 private async void btnSubmit_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         Button btn = sender as Button;
         btn.IsEnabled     = false;
         txtNotify.Content = "";
         //the message will notify the user if the operation has been done successfully
         StringBuilder messageBuilder = new StringBuilder();
         Boolean       status         = true;
         //get all the entered values from the UI
         var dateOfRequest = datePickerRequest.SelectedDate;
         var purpose       = txtBoxPurpose.Text;
         var requestType   = (TypeOfRequest)Enum.Parse(typeof(TypeOfRequest),
                                                       ((ComboBoxItem)comboBlockRequest.SelectedValue).Tag.ToString());
         ClinicDataRepository repository = new ClinicDataRepository();
         #region Checking if a user exists in DB
         if (m_patient == null)
         {
             status = false;
             messageBuilder.Append("Пользователя с таким ID не существует в базе данных\n");
         }
         #endregion
         #region Checking entered date of request
         if (dateOfRequest == null)
         {
             status = false;
             messageBuilder.Append("Дата обращения - обязательное поле для ввода.\n");
         }
         #endregion
         #region Checking entered purpose of request
         if (String.IsNullOrEmpty(purpose))
         {
             status = false;
             messageBuilder.Append("Цель обращения - обязательное поле для ввода.");
         }
         #endregion
         #region Submitting the reqiest
         if (status)
         {
             Boolean isSucceed;
             #region adding mode
             if (!isModifyingMode)
             {
                 var newRequest = new Request()
                 {
                     Patient       = m_patient,
                     DateOfRequest = dateOfRequest.GetValueOrDefault(DateTime.Now),
                     Purpose       = purpose,
                     RequestType   = requestType
                 };
                 isSucceed = await repository.AddRequest(newRequest);
             }
             #endregion
             #region modifying mode
             else
             {
                 m_request.DateOfRequest = dateOfRequest.GetValueOrDefault(DateTime.Now);
                 m_request.Purpose       = purpose;
                 m_request.RequestType   = requestType;
                 isSucceed = repository.ModifyRequest(m_request);
             }
             #endregion
             if (isSucceed && mainFrame.CanGoBack)
             {
                 mainFrame.GoBack();
             }
         }
         #endregion
         else
         {
             txtNotify.Foreground  = Brushes.Black;
             txtNotify.BorderBrush = Brushes.Red;
             txtNotify.Content     = messageBuilder.ToString();
         }
     }
     catch (InvalidOperationException)
     {
         var err = "Операция не может быть выполнена.\n" +
                   "Скорее всего какие то проблемы с базой данных. \n" +
                   "Рекомендую обратиться к разработчику";
         MessageBox.Show(err, "Ошибка");
         throw;
     }
     catch
     {
         //better to close the application than proceed with unknown error
         MessageBox.Show("Что то пошло не так. Приложение будет закрыто.", "Ошибка!");
         throw;
     }
     finally
     {
         //activate the submit button
         btnSubmit.IsEnabled = true;
     }
 }
 private async void btnSubmit_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         Button btn = sender as Button;
         btn.IsEnabled     = false;
         txtNotify.Content = "";
         //the message will notify the user if the operation has been done successfully
         StringBuilder messageBuilder = new StringBuilder();
         Boolean       status         = true;
         //get all the entered values from the UI
         var name        = txtBoxName.Text;
         var phone       = mskTxtPhone.Value;
         var dateOfBirth = datePickerBirth.SelectedDate;
         var address     = txtBoxAddress.Text;
         var gender      = (Gender)Enum.Parse(typeof(Gender),
                                              ((ComboBoxItem)comboBlockGender.SelectedValue).Tag.ToString());
         #region Checking entered name
         if (!name.IsNameValid())
         {
             status = false;
             messageBuilder.Append("Введите ФИО корректно, \nнапример: Иванов Иван Иванович.\n");
         }
         #endregion
         #region Checking entered date of birth
         if (dateOfBirth == null)
         {
             status = false;
             messageBuilder.Append("Дата рождения - обязательное поле для ввода.\n");
         }
         #endregion
         #region Checking entered address
         if (String.IsNullOrEmpty(address))
         {
             status = false;
             messageBuilder.Append("Адрес - обязательное поле для ввода.\n");
         }
         #endregion
         #region Checking entered phone number
         if (phone == null)
         {
             status = false;
             messageBuilder.Append("Номер телефона - обязателен для ввода.");
         }
         #endregion
         #region Submitting the patient
         if (status)
         {
             ClinicDataRepository repository = new ClinicDataRepository();
             #region adding mode
             if (!isModifyingMode)
             {
                 var patientCard = new PatientCard()
                 {
                     Name        = name,
                     PhoneNumber = phone.ToString(),
                     DateOfBirth = dateOfBirth.GetValueOrDefault(),
                     Address     = address,
                     Gender      = gender
                 };
                 var sucess = repository.AddPatientCard(patientCard);
                 if (await sucess)
                 {
                     txtNotify.Foreground  = Brushes.Black;
                     txtNotify.BorderBrush = Brushes.LimeGreen;
                     txtNotify.Content     = "Новая карта успешно добавлена";
                     ClearTheUI();
                 }
             }
             #endregion
             #region modifying mode
             else
             {
                 m_cardToModify.Name        = name;
                 m_cardToModify.PhoneNumber = phone.ToString();
                 m_cardToModify.DateOfBirth = dateOfBirth.GetValueOrDefault();
                 m_cardToModify.Address     = address;
                 m_cardToModify.Gender      = gender;
                 repository.ModifyPatientCard(m_cardToModify);
                 mainFrame.GoBack();
             }
             #endregion
         }
         #endregion
         else
         {
             txtNotify.Foreground  = Brushes.Black;
             txtNotify.BorderBrush = Brushes.Red;
             txtNotify.Content     = messageBuilder.ToString();
         }
     }
     #region catch, finaly
     catch (SqlException)
     {
         var err = ConfigurationSettings.AppSettings["dbError"].ToString();
         MessageBox.Show(err, "Ошибка");
         throw;
     }
     catch
     {
         MessageBox.Show("Что то пошло не так, приложение будет закрыто", "Ошибка");
         throw;
     }
     finally
     {
         //activate the submit button
         btnSubmit.IsEnabled = true;
     }
     #endregion
 }