Esempio n. 1
0
        /// <summary>
        /// Called when report details are modified and user wants to save.
        /// </summary>
        /// <param name="enableNotificantions"></param>
        public override async void OnSave(bool enableNotificantions = true)
        {
            Validate();
            if (HasErrors)
            {
                return;
            }

            if (!Model.HasConsumersAudience && !Model.HasProfessionalsAudience)
            {
                MessageBox.Show("Please enter recommended audience(s) to add a new report.");
                return;
            }

            var       errorOccurred   = false;
            Exception saveException   = null;
            var       progressService = new ProgressService();

            progressService.SetProgress("Saving report", 0, false, true);

            // await Task.Delay(500);

            var operationComplete = await progressService.Execute(() =>
            {
                base.OnSave(false);
            },
                                                                  opResult =>
            {
                if (!opResult.Status && opResult.Exception != null)
                {
                    saveException = opResult.Exception;
                    errorOccurred = true;
                }
                else
                {
                    saveException = null;
                    errorOccurred = false;
                }
            },
                                                                  new CancellationToken());

            if (operationComplete)
            {
                progressService.SetProgress("Completed", 100, true, false);

                if (!errorOccurred && saveException == null)
                {
                    Notify(string.Format("{0} {1} has been successfully saved.", Model.Name,
                                         Model.GetType().Name));
                    RegionManager.RequestNavigate(RegionNames.MainContent, new Uri(RegionNames.MainReportView, UriKind.Relative));
                }
                else
                {
                    EventAggregator.GetEvent <GenericNotificationEvent>().Publish(saveException.ToString());
                    Logger.Write(saveException, "Error saving report {0}", this.Name);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Use this to perform whatever action is needed when committed
        /// </summary>
        /// <returns></returns>
        protected async override Task <bool> OnCommitted()
        {
            ReconcileTopicsBeforeSave();

            Measure.IsLibEdit = true;

            var errorOccurred   = false;
            var progressService = new ProgressService();

            progressService.SetProgress("Saving measure", 0, false, true);

            // await Task.Delay(500);

            var operationComplete = await progressService.Execute(() =>
            {
                MeasureService.SaveMeasure(Measure, (o, e) =>
                {
                    if (e != null)
                    {
                        progressService.SetProgress("Failed", 100, true, false);
                        throw e;
                    }
                });
            },
                                                                  opResult =>
            {
                if (!opResult.Status || opResult.Exception != null)
                {
                    SynchronizationContext.Current.Post(x => {
                        errorOccurred = true;
                        var ex        = opResult.Exception;
                        Events.GetEvent <ErrorNotificationEvent>().Publish(ex);
                    }, null);
                }

                progressService.SetProgress("Completed", 100, true, false);
            },
                                                                  new CancellationToken());

            if (operationComplete && !errorOccurred)
            {
                Events.GetEvent <TopicsUpdatedEvent>().Publish(Measure.Id);
                var msg = string.Format("Measure \"{0}\" was successfully save and/or updated.", ClinicalTitle);
                Events.GetEvent <GenericNotificationEvent>().Publish(msg);
                Reset();
                return(true);
            }

            if (errorOccurred)
            {
                return(false);
            }
            return(true);
        }
Esempio n. 3
0
        /// <summary>
        /// Called when [delete] Command is triggered.
        /// </summary>
        /// <param name="entity">The entity.</param>
        protected override async void OnDelete(NursingHome entity)
        {
            if (entity == null)
            {
                return;
            }

            var result = MessageBox.Show(@"Are you sure you want to delete nursing home """ + entity.Name + @"""?",
                                         @"Delete Confirmation", MessageBoxButtons.OKCancel);

            if (result != DialogResult.OK)
            {
                return;
            }

            var errorOccurred   = false;
            var progressService = new ProgressService();

            progressService.SetProgress("Deleting nursing home", 0, false, true);

            await Task.Delay(500);

            var executedSuccessully = await progressService.Execute(() =>
            {
                using (var session = DataserviceProvider.SessionFactory.OpenSession())
                {
                    using (var trans = session.BeginTransaction())
                    {
                        var updateQuery = string.Format(@"UPDATE {0} SET IsDeleted = 1 WHERE ID = {1}",
                                                        typeof(NursingHome).EntityTableName(), entity.Id);
                        session.CreateSQLQuery(updateQuery).ExecuteUpdate();
                        session.Flush();
                        trans.Commit();
                    }
                }
            },
                                                                    opResult =>
            {
                errorOccurred = !opResult.Status && opResult.Exception != null;
                progressService.SetProgress("Completed", 100, true, false);
            }, new CancellationToken());

            if (executedSuccessully && !errorOccurred)
            {
                GetPage();
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Called when [new context report].
        /// </summary>
        /// <param name="reportView">The report view.</param>
        private async void OnNewContextReport(Report reportView)
        {
            var errorOccurred   = false;
            var progressService = new ProgressService();

            progressService.SetProgress("Creating report", 0, false, true);

            //await Task.Delay(500);
            var report = new Report(reportView.SourceTemplate);

            report.Name            = "New report based on " + report.Name;
            report.IsDefaultReport = false;

            var operationComplete = await progressService.Execute(() =>
            {
                AddNewItemCommand.Execute(report);
            },
                                                                  opResult =>
            {
                progressService.SetProgress("Completed", 100, true, false);
                if (opResult.Status && opResult.Exception != null)
                {
                    errorOccurred = true;
                    LogEntityError(opResult.Exception.GetBaseException(), typeof(Report), Title);
                }
                else
                {
                    errorOccurred = false;
                }
            }, new CancellationToken());

            if (operationComplete && !errorOccurred)
            {
                OnLoad();
                OnNavigateToDetails(report);
            }
        }
        public override async void OnSave(bool enableNotificantions = false)
        {
            if (string.IsNullOrEmpty(Model.Name) || string.IsNullOrEmpty(Model.GroupPracticePacId))
            {
                MessageBox.Show("Orginization Name and Group Id fields are required", "Invalid Input");
                return;
            }

            int num;

            if (int.TryParse(NumberOfMembers, out num))
            {
                Model.NumberofGroupPracticeMembers = num;
            }
            else if (!string.IsNullOrEmpty(NumberOfMembers))
            {
                MessageBox.Show("Please enter a valid number for Group Practice Members", "Invalid Input");
                return;
            }

            Validate();
            Model.Validate();
            Model.Addresses.ForEach(a => a.Validate());

            if (HasErrors || Model.HasErrors || Model.Addresses.Any(a => a.HasErrors))
            {
                return;
            }

            try
            {
                using (var session = DataServiceProvider.SessionFactory.OpenStatelessSession())
                {
                    if (session.Query <MedicalPractice>().FirstOrDefault(x => x.Id != Model.Id && x.GroupPracticePacId == Model.GroupPracticePacId) != null)
                    {
                        MessageBox.Show("There is already a medical practice with the same Group Practice Pac Id. Group Practice Pac Id must be unique.", "Notification");
                        return;
                    }
                }

                Model.IsEdited = true;

                var       errorOccurred   = false;
                Exception errorException  = null;
                var       progressService = new ProgressService();

                progressService.SetProgress("Saving " + Inflector.Titleize2(typeof(MedicalPractice).Name), 0, false, true);

                // await Task.Delay(500);

                var operationComplete = await progressService.Execute(() => OnSave(Model),
                                                                      result =>
                {
                    if (!result.Status && result.Exception != null)
                    {
                        errorOccurred  = true;
                        errorException = result.Exception;
                    }
                    else
                    {
                        errorOccurred  = false;
                        errorException = null;
                    }
                },
                                                                      new CancellationToken());

                if (operationComplete)
                {
                    progressService.SetProgress("Completed", 100, true, false);

                    if (!errorOccurred || errorException == null)
                    {
                        EventAggregator.GetEvent <GenericNotificationEvent>()
                        .Publish(string.Format("MedicalPractice {0} has been saved successfully.", Model.Name));
                        EventAggregator.GetEvent <RequestLoadMappingTabEvent>().Publish(typeof(MedicalPracticeEditViewModel));
                        NavigateBack();
                    }
                    else
                    {
                        Logger.Write(errorException, "Error saving Medical Practice \"{0}\"", Model.Name);
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.Write(exc, "Error saving Medical Practice \"{0}\"", Model.Name);
            }
        }
        /// <summary>
        /// Called when [save2].
        /// </summary>
        /// <param name="navigateback">if set to <c>true</c> [navigateback].</param>
        /// <param name="enableNotificantions">if set to <c>true</c> [enable notificantions].</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">Hospital can not be null.</exception>
        public async Task <bool> OnSave2(bool navigateback = false, bool enableNotificantions = false)
        {
            try
            {
                if (HospitalToSave == null)
                {
                    throw new ArgumentNullException(@"Hospital can not be null.");
                }

                if (!ValidateHospital())
                {
                    return(false);
                }

                var       errorOccurred   = false;
                Exception saveException   = null;
                var       progressService = new ProgressService();

                progressService.SetProgress("Saving Hospital", 0, false, true);

                await Task.Delay(500);

                var operationComplete = await progressService.Execute(() =>
                {
                    var selectedRegionTypeContext = ConfigService.HospitalRegion.SelectedRegionType;

                    Hospital archivedHospital = null;
                    if (HospitalToSave.Hospital != null &&
                        HospitalToSave.Hospital.IsSourcedFromBaseData)
                    {
                        archivedHospital           = Service.CreateHospitalArchive(HospitalToSave.Hospital);
                        HospitalToSave.Hospital.Id = 0;
                        HospitalToSave.Hospital.IsSourcedFromBaseData = false;
                    }

                    // Categories
                    HospitalToSave.Hospital.Categories.Clear();

                    var selecterdCategories =
                        HospitalToSave.Categories.Where(c => c.IsSelected)
                        .Select(item => ((HospitalCategory)item.Model))
                        .ToList();
                    foreach (var category in selecterdCategories)
                    {
                        HospitalToSave.Hospital.Categories.Add(category);
                    }

                    // Selected Region
                    var selectedRegion = HospitalToSave.SelectedRegionViewModel;
                    if (CheckSelectedRegionHasChanged(HospitalToSave.Hospital, selectedRegion))
                    // Check to see that the regions are different.
                    {
                        if (selectedRegion != null)
                        {
                            if (selectedRegion is CustomRegion)
                            {
                                HospitalToSave.Hospital.CustomRegion = selectedRegion as CustomRegion;
                            }
                            else if (selectedRegion is HealthReferralRegion)
                            {
                                HospitalToSave.Hospital.HealthReferralRegion = selectedRegion as HealthReferralRegion;
                                //HospitalToSave.Hospital.CustomRegion = null;
                            }
                            else if (selectedRegion is HospitalServiceArea)
                            {
                                HospitalToSave.Hospital.HospitalServiceArea = selectedRegion as HospitalServiceArea;
                                //HospitalToSave.Hospital.CustomRegion = null;
                            }
                        }
                        else
                        {
                            if (selectedRegionTypeContext == typeof(CustomRegion))
                            {
                                HospitalToSave.Hospital.CustomRegion = null;
                            }
                            else if (selectedRegionTypeContext == typeof(HospitalServiceArea))
                            {
                                HospitalToSave.Hospital.HospitalServiceArea = null;
                                //HospitalToSave.Hospital.CustomRegion = null;
                            }
                            else if (selectedRegionTypeContext == typeof(HealthReferralRegion))
                            {
                                HospitalToSave.Hospital.HealthReferralRegion = null;
                                //HospitalToSave.Hospital.CustomRegion = null;
                            }
                        }
                    }

                    // CMS PRovider Ids

                    if (HospitalToSave.NameOfNewCmsProvider != null && !HospitalToSave.Hospital.CmsProviderID.EqualsIgnoreCase(HospitalToSave.NameOfNewCmsProvider))
                    {
                        var existingHospital =
                            Service.Get <Hospital>(
                                h =>
                                h.CmsProviderID.ToLower() == HospitalToSave.NameOfNewCmsProvider.ToLower() &&
                                h.State.ToLower() == HospitalToSave.Hospital.State.ToLower() &&
                                !h.IsArchived && !h.IsDeleted);

                        if (existingHospital != null && existingHospital.IsSourcedFromBaseData)
                        {
                            Hospital archivedHospital2             = Service.CreateHospitalArchive(existingHospital);
                            existingHospital.Id                    = 0;
                            existingHospital.IsSourcedFromBaseData = false;
                            existingHospital.CmsProviderID         = null;
                            Service.Save(existingHospital);
                            archivedHospital2.LinkedHospitalId = existingHospital.Id;
                            Service.Save(archivedHospital2);
                        }
                        else if (existingHospital != null && !existingHospital.IsSourcedFromBaseData)
                        {
                            existingHospital.CmsProviderID = null;
                            Service.Save(existingHospital);
                        }

                        HospitalToSave.Hospital.CmsProviderID = CurrentHospitalViewModel.NameOfNewCmsProvider;
                    }
                    else if (HospitalToSave.NameOfNewCmsProvider == null)
                    {
                        HospitalToSave.Hospital.CmsProviderID = null;
                    }

                    Service.Save(HospitalToSave.Hospital);

                    //HospitalToSave.Hospital = result.Model;
                    if (archivedHospital != null)
                    {
                        archivedHospital.LinkedHospitalId = HospitalToSave.Hospital.Id;
                        Service.Save(archivedHospital);
                    }

                    //Thread.Sleep(20000);

                    //await Service.SaveAsync(HospitalToSave.Hospital, result =>
                    //{
                    //    if (result.Status)
                    //    {
                    //        HospitalToSave.Hospital = result.Model;
                    //        if (archivedHospital != null)
                    //        {
                    //            archivedHospital.LinkedHospitalId = HospitalToSave.Hospital.Id;
                    //            Service.Save(archivedHospital);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        if (!result.Status && result.Exception != null)
                    //        {
                    //            throw result.Exception;
                    //        }
                    //    }
                    //});
                }, result =>
                {
                    if (result.Status)
                    {
                        errorOccurred = false;
                        saveException = null;
                    }
                    else
                    {
                        if (result.Exception != null)
                        {
                            errorOccurred = true;
                            saveException = result.Exception;
                        }
                    }
                }, new CancellationToken());

                if (operationComplete)
                {
                    progressService.SetProgress("Completed", 100, true, false);

                    if (errorOccurred && saveException != null)
                    {
                        Logger.Write(saveException, "Error saving details for hospital");
                        EventAggregator.GetEvent <ErrorNotificationEvent>().Publish(saveException);
                    }
                    else
                    {
                        if (navigateback)
                        {
                            EventAggregator.GetEvent <GenericNotificationEvent>().Publish(string.Format("{2}Hospital {0} has been {1}", HospitalToSave.Hospital.Name, IsCreatingNewHospital ? "added" : "updated", IsEditingHospitalsList && !navigateback ? "Previous " : string.Empty));

                            CurrentHospitalViewModel.InEditCreateMode = false;
                            ExecuteNavigateBack();
                        }
                        else
                        {
                            EventAggregator.GetEvent <GenericNotificationEvent>().Publish(string.Format("{2}Hospital {0} has been {1}", HospitalToSave.Hospital.Name, IsCreatingNewHospital ? "added" : "updated", IsEditingHospitalsList && !navigateback ? "Previous " : string.Empty));
                        }
                        HospitalToSave = null;
                    }
                }
            }
            catch (Exception ex)
            {
                EventAggregator.GetEvent <ErrorNotificationEvent>().Publish(ex);
                return(false);
            }

            return(true);
        }
Esempio n. 7
0
        /// <summary>
        /// Called when report is deleted.
        /// </summary>
        /// <param name="report">The report.</param>
        protected async override void OnDelete(Report report)
        {
            if (report.WebsitesForReportDisplay != null && report.WebsitesForReportDisplay.Count > 0)
            {
                MessageBox.Show("The report is already been used in a website, please remove it from the website before deleting it", "Delete report", MessageBoxButton.OK);
                return;
            }

            if (MessageBox.Show("Are you sure you want to delete this report?", "Delete Report", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
            {
                return;
            }

            var msg = string.Format("{0} report has been deleted.", report.Name);

            var errorOccurred   = false;
            var progressService = new ProgressService();

            progressService.SetProgress("Deleting report", 0, false, true);

            // await Task.Delay(500);

            var operationComplete = await progressService.Execute(() =>
            {
                using (var session = DataserviceProvider.SessionFactory.OpenSession())
                {
                    using (var trans = session.BeginTransaction())
                    {
                        try
                        {
                            session.Evict(report);
                            session.Delete(report);
                            session.Flush();
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            },
                                                                  opResult =>
            {
                if (!opResult.Status || opResult.Exception != null)
                {
                    errorOccurred = true;
                    EventAggregator.GetEvent <GenericNotificationEvent>().Publish(opResult.Exception.GetBaseException().ToString());
                    Logger.Write(opResult.Exception, "Error deleting report {0}", report.Name);
                }

                progressService.SetProgress("Completed", 100, true, false);
            },
                                                                  new CancellationToken());

            if (operationComplete && !errorOccurred)
            {
                OnLoad();
                Notify(msg);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Called when save is clicked to save the report changes.
        /// </summary>
        protected override async void OnSave()
        {
            base.OnSave();

            if (HasErrors)
            {
                return;
            }

            if (!(Audiences[1].IsSelected || Audiences[2].IsSelected))
            {
                MessageBox.Show(
                    "Please enter a report type, report name, and recommended audience(s) to add a new report.");
                return;
            }

            try
            {
                var errorOccurred   = false;
                var progressService = new ProgressService();

                progressService.SetProgress("Creating report", 0, false, true);

                //await Task.Delay(500);

                var operationComplete = await progressService.Execute(() =>
                {
                    //Get all selected enum values but the default/non-selected value of zero "0"
                    var selectedAudiences =
                        Audiences.Where(a => a.IsSelected && a.Value != 0).Select(a => a.Enum).ToList();
                    //.Aggregate<AudienceModel, uint>(0, (current, a) => current + (uint)a.Value);
                    var factory  = new ReportManifestFactory();
                    var manifest = factory.InstalledManifests.FirstOrDefault(x => x.Name == ReportType);
                    var report   = new Report(manifest)
                    {
                        Name = Title
                    };                                                  //, Audiences = selectedAudiences.ToList()
                    AddNewItemCommand.Execute(report);
                },
                                                                      opResult =>
                {
                    progressService.SetProgress("Completed", 100, true, false);
                    if (opResult.Status && opResult.Exception != null)
                    {
                        errorOccurred = true;
                        LogEntityError(opResult.Exception.GetBaseException(), typeof(Report), Title);
                    }
                    else
                    {
                        errorOccurred = false;
                    }
                }, new CancellationToken());

                if (operationComplete && !errorOccurred)
                {
                    OnLoad();
                    Notify(String.Format("New report {0} has been added", Title));
                }
            }
            catch (Exception exc)
            {
                LogEntityError(exc, typeof(Report), Title);
            }
            finally
            {
                Reset();
            }
        }
        /// <summary>
        /// Called when [delete].
        /// </summary>
        /// <param name="entity">The entity.</param>
        protected override async void OnDelete(db.Physician entity)
        {
            if (entity == null)
            {
                return;
            }

            var result =
                MessageBox.Show(@"Are you sure want to delete the data for this physician, """ + entity.Name + @"""?", @"Delete Confirmation", MessageBoxButtons.OKCancel);

            if (result != DialogResult.OK)
            {
                return;
            }

            var       errorOccurred   = false;
            Exception errorException  = null;
            var       progressService = new ProgressService();

            progressService.SetProgress("Deleting physican", 0, false, true);

            //await Task.Delay(500);

            string entityName          = entity.Name;
            var    executedSuccessully = await progressService.Execute(() =>
            {
                using (var session = DataserviceProvider.SessionFactory.OpenSession())
                {
                    using (var trans = session.BeginTransaction())
                    {
                        try
                        {
                            var updateQuery = string.Format(@"UPDATE {0} SET IsDeleted = 1 WHERE Id = {1} AND IsDeleted = 0",
                                                            typeof(db.Physician).EntityTableName(),
                                                            entity.Id);
                            session.CreateSQLQuery(updateQuery).ExecuteUpdate();
                            session.Flush();
                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw;
                        }
                    }
                }
            },
                                                                       opResult =>
            {
                if (!opResult.Status && opResult.Exception != null)
                {
                    errorOccurred  = true;
                    errorException = opResult.Exception;
                }
                else
                {
                    errorOccurred = true;
                }
            }, new CancellationToken());

            progressService.SetProgress("Completed", 100, true, false);

            if (errorOccurred && errorException != null)
            {
                Logger.Write(errorException, "Error deleting physician \"{0}\"", entity.Name);
                LogEntityError(errorException, typeof(db.Physician), entityName);
                return;
            }

            CollectionItems.Remove(entity);
            CollectionItems.Refresh();

            Notify(string.Format("{0} {1} has been deleted.", entityName,
                                 Inflector.Titleize(typeof(db.Physician).Name)));
        }
        /// <summary>
        /// Called when [save].
        /// </summary>
        /// <param name="enableNotificantions">if set to <c>true</c> [enable notificantions].</param>
        public override async void OnSave(bool enableNotificantions = true)
        {
            Validate();
            Model.Validate();

            if (HasErrors || Model.HasErrors)
            {
                return;
            }

            //TODO: uncomment this code for npi uniqueness validation
            //if (!IsNpiUnique())
            //{
            //    var result = MessageBox.Show("There is already a physician with the same NPI. NPI must be unique.", "Notification");
            //    return;
            //}

            if (!ValidateAddresses())
            {
                if (MessageBox.Show(string.Format("A location/address nor a medical practice with a defined locations/addresses has not been associated with physician \"{1}\".{0}Please press Cancel and go to the \"Hospital Affliation and Locations\" tab{0}to associate a location/address or medical practice with this physician \"{1}\".{0}If proceeding to save the physician \"{1}\" with out associating a location or a medical practice,{0}this physician may not appear in your published website.", Environment.NewLine, Model.Name), "Physical Details Validation", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            try
            {
                var       errorOccurred   = false;
                Exception errorException  = null;
                var       progressService = new ProgressService();

                progressService.SetProgress("Saving physician", 0, false, true);

                //await Task.Delay(500);

                GenderEnum val;
                if (Enum.TryParse(SelectedGender, true, out val))
                {
                    Model.Gender = val;
                }
                if (SelectedMedicalAssignement != null && !string.IsNullOrEmpty(SelectedMedicalAssignement.EnumName))
                {
                    Model.AcceptsMedicareAssignment =
                        EnumExtensions.GetEnumValueFromString <db.MedicalAssignmentEnum>(
                            SelectedMedicalAssignement.EnumName);
                }

                Model.ForeignLanguages = new List <string>();
                if (!string.IsNullOrEmpty(Languages))
                {
                    Languages.Split(',').ToList().ForEach(x => Model.ForeignLanguages.Add(x));
                }

                Model.AffiliatedHospitals.Clear();
                Hospitals.ToList().ForEach(x => Model.AffiliatedHospitals.Add(new db.PhysicianAffiliatedHospital
                {
                    HospitalCmsProviderId = GetCmsProviderId(x)
                }));

                //	DeletedPhysicianAddressList was acting as an omni buffer for both Physician and MedicalPractice addresses.
                //	This is going to change for a buffer for both Physician and 'Associated' MedicalPractice addresses.
                //	Scrap This:  If the address.MedicalPractice name is null, delete from Physician Addresses; else delete from MPAssociated Addresses
                //	Scrap This:  Current logic is fine.  It deletes from both list in either case.  Since a single Address(Id) object cannot be both
                //				 Physician and MedicalPractice, there is no issue.
                foreach (var address in DeletedPhysicianAddressList)
                {
                    var physicianaAd = Model.Addresses != null
                        ? Model.Addresses.FirstOrDefault(x => x.Id == address.Id)
                        : null;

                    if (physicianaAd != null)
                    {
                        Model.Addresses.Remove(physicianaAd);
                    }

                    Model.PhysicianMedicalPractices.ToList().ForEach(pmp =>
                    {
                        if (pmp.AssociatedPMPAddresses.Contains(address.Id))
                        {
                            pmp.AssociatedPMPAddresses.Remove(address.Id);
                        }
                    });
                    Model.PhysicianMedicalPractices.ToList().RemoveAll(pmp => pmp.AssociatedPMPAddresses.Count == 0);

                    //	var medAddress = address as Monahrq.Infrastructure.Domain.Physicians.MedicalPracticeAddress;
                    //	if (medAddress != null)
                    //	{
                    //		var currentPMP = Model.PhysicianMedicalPractices.Where(pmp => pmp.MedicalPractice.Id == medAddress.MedicalPractice.Id).Single();
                    //		currentPMP.AssociatedPMPAddresses.Remove(address.Id);
                    //		if (currentPMP.AssociatedPMPAddresses.Count == 0)
                    //			Model.PhysicianMedicalPractices.Remove(currentPMP);
                    //	}
                }


                if (Model.States == null)
                {
                    Model.States = new List <string>();
                }

                if (Model.Addresses == null)
                {
                    Model.Addresses = new List <db.PhysicianAddress>();
                }

                if (Model.Addresses.Any() ||
                    Model.PhysicianMedicalPractices.Any(pmp => pmp.MedicalPractice.Addresses.Any()))
                {
                    Model.States.Clear();
                }

                if (Model.Addresses != null && Model.Addresses.Any())
                {
                    Model.Addresses.DistinctBy(x => x.State).Select(x => x.State).ToList().ForEach(add =>
                    {
                        if (!Model.States.Contains(add))
                        {
                            Model.States.Add(add);
                        }
                    });
                }
                if (Model.PhysicianMedicalPractices.Any(pmp => pmp.MedicalPractice.Addresses.Any()))
                {
                    Model.PhysicianMedicalPractices.Select(pmp => pmp.MedicalPractice).ToList()
                    .ForEach(mp => mp.Addresses.DistinctBy(x => x.State)
                             .Select(x => x.State).ToList().ForEach(add =>
                    {
                        if (!Model.States.Contains(add))
                        {
                            Model.States.Add(add);
                        }
                    }));
                }

                if (!Model.IsPersisted && !Model.States.Any())
                {
                    Model.States.Add(ConfigurationService.HospitalRegion.DefaultStates.OfType <string>().ToList().First());
                }

                if (Model.States != null && Model.States.Any())
                {
                    Model.States = Model.States.OrderBy(state => state).ToList();
                }

                DeletedPhysicianAddressList = new ObservableCollection <Address>();

                var operationComplete = await progressService.Execute(() =>
                {
                    //var configService = ServiceLocator.Current.GetInstance<IConfigurationService>();

                    Model.IsEdited = true;

                    using (var session = DataServiceProvider.SessionFactory.OpenSession())
                    {
                        //using (var trans = session.BeginTransaction())
                        {
                            try
                            {
                                OnSaveInternal(session, Model);

                                //trans.Commit();
                                session.Flush();
                                //
                            }
                            catch (Exception exc)
                            {
                                Logger.Write(exc, "Error saving details for physician \"{0}\"", Model.Name);
                                throw;
                            }
                        }
                    }

                    //base.OnSave(false);
                },
                                                                      opResult =>
                {
                    if (!opResult.Status && opResult.Exception != null)
                    {
                        errorOccurred  = true;
                        errorException = opResult.Exception;
                    }
                    else
                    {
                        errorOccurred  = false;
                        errorException = null;
                    }
                }, new CancellationToken());

                if (operationComplete)
                {
                    progressService.SetProgress("Completed", 100, true, false);

                    if (!errorOccurred && errorException == null)
                    {
                        Notify(string.Format("{1} \"{0}\" has been successfully saved.", Model.Name, typeof(db.Physician).Name));
                        NavigateBack();
                    }
                    else
                    {
                        Logger.Write(errorException, "Error saving details for physician \"{0}\"", Model.Name);
                    }
                }
            }
            catch (Exception exc)
            {
                // the error handling in this application is a mess and I don't have enough time to fix it the right way... #sorry
                Logger.Write(exc, "Error saving details for physician \"{0}\"", Model.Name);
            }
        }
        //private bool _saving;
        /// <summary>
        /// Called when [save].
        /// </summary>
        /// <param name="enableNotificantions">if set to <c>true</c> [enable notificantions].</param>
        public override async void OnSave(bool enableNotificantions = false)
        {
            _saveInitiated = true;
            // if (_saving) return;
            Model.Validate();
            if (HasErrors || Model.HasErrors)
            {
                return;
            }
            DateTime participationDate;

            DateTime.TryParse(DateApproved, out participationDate);
            Model.ParticipationDate = participationDate;

            try
            {
                //_saving = true;
                var       errorOccurred      = false;
                Exception operationException = null;
                var       progressService    = new ProgressService();

                progressService.SetProgress("Saving Nursing Home", 0, false, true);

                await Task.Delay(500);

                var operationComplete = await progressService.Execute(() =>
                {
                    if (Model.Certification == NursingHomeType[0])
                    {
                        Model.Certification = null;
                    }
                    Model.ChangedOwnership_12Mos = ConvertToBoolean(SelectedProviderChangedOwnership) ?? false;
                    Model.ResFamCouncil          = EnumExtensions.GetEnumValueFromString <ResFamCouncilEnum>(SelectedCouncil);
                    Model.SprinklerStatus        = SelectedSprinklerSystem ==
                                                   SprinklerStatusEnum.DataNotAvailable.GetDescription()
                        ? SprinklerStatusEnum.DataNotAvailable
                        : EnumExtensions.GetEnumValueFromString <SprinklerStatusEnum>(SelectedSprinklerSystem);
                    Model.InHospital            = ConvertToBoolean(SelectedInHospital);
                    Model.InRetirementCommunity = ConvertToBoolean(SelectedInRetirementCommunity);
                    Model.HasSpecialFocus       = ConvertToBoolean(SelectedSpecialFocus);
                    if (Model.Accreditation == AccreditationOptions[0])
                    {
                        Model.Accreditation = null;
                    }
                    if (SelectedCounty != null)
                    {
                        Model.CountySSA  = SelectedCounty.CountySSA;
                        Model.CountyName = !string.IsNullOrEmpty(SelectedCounty.Name)
                            ? SelectedCounty.Name.Replace("County", "")
                            : null;
                    }

                    if (HasProviderIdChanged)
                    {
                        using (var session = DataServiceProvider.SessionFactory.OpenSession())
                        {
                            var nursingHome =
                                session.Query <NursingHome>()
                                .FirstOrDefault(x => x.ProviderId == Model.ProviderId && !x.IsDeleted);
                            if (nursingHome != null && nursingHome.Id != Model.Id)
                            {
                                var msg = string.Format("Assigning a different CMS Provider Number will un-assign this number from one of the existing nursing homes, {0}. You must re-assign a different CMS Provider ID to {1}.",
                                                        nursingHome.Name, nursingHome.Name);
                                var prompt = MessageBox.Show(msg, @"Warning", MessageBoxButtons.OKCancel);
                                if (prompt == DialogResult.Cancel)
                                {
                                    return;
                                }

                                using (var trans = session.BeginTransaction())
                                {
                                    nursingHome.ProviderId = null;
                                    session.SaveOrUpdate(nursingHome);
                                    trans.Commit();
                                }
                            }
                        }
                    }

                    base.OnSave(false);
                }, opResult =>
                {
                    if (opResult.Status)
                    {
                        _saveInitiated     = false;
                        errorOccurred      = false;
                        operationException = null;
                    }
                    else if (!opResult.Status && opResult.Exception != null)
                    {
                        errorOccurred      = true;
                        operationException = opResult.Exception;
                    }
                }, new CancellationToken());

                if (operationComplete)
                {
                    EventAggregator.GetEvent <StatusbarUpdateEvent>().Publish(new StatusbarUpdateEventObject {
                        ProcessingText = "Complete", Progress = 100, Reset = true, IsIndeterminate = false
                    });

                    if (!errorOccurred && operationException == null)
                    {
                        Notify(string.Format("\"{0}\" Nursing Home has been saved successfully.", Model.Name));
                        NavigateBack();
                    }
                    else
                    {
                        Logger.Write(operationException, "Error saving Nursing Home \"{0}\"", Model.Name);
                        NotifyError(operationException, typeof(NursingHome), Model.Name);
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.Write(exc, "Error saving Nursing Home \"{0}\"", Model.Name);
                NotifyError(exc, typeof(NursingHome), Model.Name);
            }
        }