Esempio n. 1
0
        public override int SaveChanges()
        {
            var entities = ChangeTracker.Entries()
                           .Where(x => x.State == EntityState.Added || x.State == EntityState.Modified)
                           .GroupBy(x => x.State, x => x.Entity);

            var    now         = DateTime.Now;
            string currentUser = _usernameProvider?.GetUsername() ?? "System";

            foreach (var entityState in entities)
            {
                foreach (var item in entityState)
                {
                    if (entityState.Key == EntityState.Added)
                    {
                        this.SetPropertyValue(item, "CreatedDate", now);
                    }

                    this.SetPropertyValue(item, "ModifiedDate", now);
                    this.SetPropertyValue(item, "ModifiedBy", currentUser);
                }
            }

            return(base.SaveChanges());
        }
        protected void PopulateAuditFieldsBeforeSave(DomainModelBase toValue)
        {
            if (toValue == null)
            {
                throw new ArgumentNullException(nameof(toValue), $"{nameof(toValue)} is null.");
            }

            if (toValue.Id == 0)
            {
                toValue.CreatedBy   = _UsernameProvider.GetUsername();
                toValue.CreatedDate = DateTime.UtcNow;
            }

            toValue.LastModifiedBy   = _UsernameProvider.GetUsername();
            toValue.LastModifiedDate = DateTime.UtcNow;
        }
Esempio n. 3
0
        private void CheckMessage(string message)
        {
            if (message.StartsWith("@exit"))
            {
                _shouldExit = true;
                LeaveChat($"{_usernameProvider.GetUsername()} waves goodbye");
            }
            else if (message.StartsWith("@user"))
            {
                var oldUser = _usernameProvider.GetUsername();
                if (Colors.ContainsKey(oldUser))
                {
                    Colors.Remove(oldUser);
                }
                var newUsername = message.Replace("@user", "").Trim();

                Colors.Add(newUsername, ConsoleColor.Cyan);
                _usernameProvider.SetUsername(newUsername);
                JoinChat($"Ahoy! {oldUser} changed name to {newUsername}.");
            }
            else
            {
                MessageChat(message);
            }
        }
Esempio n. 4
0
        public ELRSearchRules NoDuplicateTemplateNames()
        {
            Rule(async q =>
            {
                string name = q.TemplateName;
                int id      = q.TemplateId;

                bool nameExists = await merlinReadContext.ElrSearchTemplates
                                  .AnyAsync(template => template.DsName == name &&
                                            (template.IdAdded == usernameProvider.GetUsername() || template.CdType == "MASTER"));

                bool exists = await merlinReadContext.ElrSearchTemplates
                              .Where(e => e.Id.Equals(id))
                              .Select(e => e.DsName == name).FirstOrDefaultAsync();


                if (nameExists && !exists)
                {
                    Error($"A Template with the name '{name}' already exists.", "templateName");
                }
            });

            return(this);
        }
Esempio n. 5
0
        private void Initialize(IFeatureRepository repository)
        {
            string username = _UsernameProvider.GetUsername();

            Initialize(repository, username);
        }
Esempio n. 6
0
        public async Task Execute(RefilterObservations command)
        {
            //delete from XBOX

            var connection = writeContext.Database
                             .GetDbConnection()
                             .EnsureOpen();

            using (var transaction = connection.BeginTransaction())
            {
                foreach (var observationKey in command.ObservationKeys)
                {
                    string sql = @"Execute [sp_ElrReFilter] @observationKey, @userId";

                    await connection.ExecuteAsync(sql, new { observationKey, userId = usernameProvider.GetUsername() }, transaction);
                }

                transaction.Commit();
            }
        }
Esempio n. 7
0
        public async Task Execute(SaveSurveyAnswers command)
        {
            var questionStorageMap = await repos.GetQuestionStorageMap(command.SurveyId);

            var currentAnswers = await repos.Get(new GetSurveyAnswers
            {
                CaseId     = command.CaseId,
                SurveyId   = command.SurveyId,
                ProfileId  = command.ProfileId,
                OutbreakId = command.OutbreakId
            });

            //unwrap jArrays to complex types
            SurveyAnswerBindingHelpers.Bind(command.Answers);

            var answers = command.Answers.ToDictionary(entry => entry.Key.ToUpper(), entry => entry.Value);

            //get only the differences
            var deltas = SurveyAnswerHelpers.GetDeltas(currentAnswers, answers);

            //if no delta, exit
            if (!deltas.Any())
            {
                return;
            }

            var writer = COR <SurveyAnswerWriteContext> .CreateChain(
                new SymptomWriteHandler(),
                new TravelHistoryWriteHandler(),
                new MappedWriteHandler(dataServices),
                new RepeaterWriteHandler(),
                new MultipleWriteHandler(),
                new DefaultWriteHandler());

            var allkeys = deltas
                          .Select(delta => delta.Key)
                          .ToList();

            var storageMapping = writeContext.SurveyObjectMapping
                                 .Where(mapping => mapping.CdMappingtype == "TARGETDS")
                                 .Where(mapping => allkeys.Contains(mapping.IdQuestion))
                                 .ToDictionary(mapping => mapping.IdQuestion.ToUpper());

            var surveyInstanceId = await repos.GetSurveyInstanceId(command.ProfileId, command.CaseId, command.OutbreakId);

            var connection = writeContext.Database.GetDbConnection().EnsureOpen();

            using (var transaction = writeContext.Database.BeginTransaction().GetDbTransaction())
            {
                //TODO:  This needs better DB design
                //if no survey instance, create one
                if (surveyInstanceId == 0)
                {
                    surveyInstanceId = (int)await sequencerGenerator.GetNextAsync(SequenceType.SurveyInstance);

                    var instance = new SurveyInstance
                    {
                        IdSurveyInstance = surveyInstanceId.Value,
                        IdProfile        = command.ProfileId,
                    };

                    if (command.OutbreakId != null)
                    {
                        instance.CdEntityType = "O";
                        instance.IdEntity     = command.OutbreakId;
                    }

                    if (command.CaseId != null)
                    {
                        instance.CdEntityType = "C";
                        instance.IdEntity     = command.CaseId;
                    }

                    await writeContext.SurveyInstance.AddAsync(instance);

                    await writeContext.SaveChangesAsync();
                }
                //end

                var context = new SurveyAnswerWriteContext
                {
                    DB                 = writeContext,
                    CaseId             = command.CaseId,
                    ProfileId          = command.ProfileId,
                    OutbreakId         = command.OutbreakId,
                    SurveyInstanceId   = surveyInstanceId.Value, //should be assigned a value by this point
                    UserId             = usernameProvider.GetUsername(),
                    Timestamp          = DateTime.Now,
                    QuestionStorageMap = questionStorageMap
                };

                context.Transaction = transaction;
                context.Connection  = connection;

                //apply the changes
                foreach (var delta in deltas)
                {
                    context.Delta = delta;

                    await writer.HandleAsync(context);

                    //need to mark question as answered
                    if (SurveyAnswerBindingHelpers.IsQuestion(delta.Key))
                    {
                        var param = new
                        {
                            questionId = delta.Key
                        };
                        try
                        {
                            string sql = @"update survey_question_bank
                                set IN_ANSWERED = 1
                                where id_question = @questionId
                                and IN_ANSWERED = 0;";

                            await connection.ExecuteAsync(sql, param, 1, transaction);
                        }
                        catch (Exception e)
                        {
                            //do nothing for now
                        }
                    }
                }
                transaction.Commit();
            }
        }
Esempio n. 8
0
        private async Task SaveOutbreak(UpdateOutbreak command)
        {
            var outbreak = await writeContext.Outbreak
                           .Include(ob => ob.OutbreakEvents)
                           .Include(ob => ob.OutbreakSymptoms)
                           .FirstAsync(ob => ob.IdOutbreak == command.OutbreakId);

            using (var transaction = writeContext.Database.BeginTransaction())
            {
                //calculate the event date
                outbreak.DtOutbreakEvent = new DateTime?[]
                {
                    outbreak.DtEarliestOnset,
                    outbreak.DtEarliestExposure,
                    outbreak.DtChdNotified,
                    outbreak.DtOutbreakEvent
                }
                .Where(d => d.HasValue)
                .OrderBy(d => d)
                .First();

                //so all events have the same timestamp
                var eventDate = DateTime.Now;

                await ReplaceEvents(outbreak, OutbreakEventType.Investigation, command.InvestigationMethods, eventDate, CodeType.OutbreakInvestigation);
                await ReplaceEvents(outbreak, OutbreakEventType.StudyDesign, command.StudyDesigns, eventDate, CodeType.OutbreakStudyDesign);
                await ReplaceEvents(outbreak, OutbreakEventType.MultiCounty, command.OtherCountiesList, eventDate, CodeType.County);
                await ReplaceEvents(outbreak, OutbreakEventType.MultiCountry, command.OtherCountriesList, eventDate, CodeType.Country, CodeType.Region);
                await ReplaceEvents(outbreak, OutbreakEventType.MultiState, command.OtherStatesList, eventDate, CodeType.State);
                await ReplaceEvents(outbreak, OutbreakEventType.Regulatory, command.RegulatoryAgencies, eventDate, CodeType.OutbreakRegulatory);

                await CreateEvent(outbreak, OutbreakEventType.CaseDefinition, command.CaseDefinition, eventDate);
                await CreateEvent(outbreak, OutbreakEventType.LabFindings, command.LabFindings, eventDate);
                await CreateEvent(outbreak, OutbreakEventType.Closure, command.Decisions, eventDate, OutbreakEventType.ConclusionNotes);
                await CreateEvent(outbreak, OutbreakEventType.Closure, command.Recommendations, eventDate, OutbreakEventType.Recommendations);
                await CreateEvent(outbreak, OutbreakEventType.ProcessImprovements, command.ImprovementAreas, eventDate);
                await CreateEvent(outbreak, OutbreakEventType.EpiComPostId, command.PostId.ToString(), eventDate);

                ReplaceSymptoms(outbreak, command.Symptom, command.OtherSymptom);

                outbreak.NmOutbreak = command.EventName;

                //if ICD9 changes update all associated cases
                if (outbreak.CdIcd9 != command.DiseaseHazard)
                {
                    string sql = "update dbo.epi_case set CD_ICD9 = @icd9 where id_outbreak = @outbreakId";

                    var connection = writeContext.Database.GetDbConnection().EnsureOpen();

                    await connection.ExecuteAsync(sql, new
                    {
                        icd9       = command.DiseaseHazard,
                        outbreakId = command.OutbreakId
                    }, transaction.GetDbTransaction());

                    outbreak.CdIcd9 = command.DiseaseHazard;

                    //only need to ensure a survey is created/exists when ICD9 changes
                    await EnsureOutbreakSurvey(outbreak);
                }

                outbreak.CdCountyInitiating      = command.County;
                outbreak.InMultiCounty           = command.OtherCountiesAffected;
                outbreak.InMultiState            = command.OtherStatesAffected;
                outbreak.DsStateConsulted        = command.StaffConsulted;
                outbreak.NmInvestigator          = command.Investigator;
                outbreak.CdModeTransmission      = command.TransmissionMode;
                outbreak.InFoodWater             = command.FoodOrWaterRelated;
                outbreak.InVehicleFw             = command.IsVehicleIdentified;
                outbreak.DsVehicleFw             = command.Vehicle;
                outbreak.InHealthcare            = command.HealthRelated;
                outbreak.CdVehicleIdentified     = command.CauseForOutbreak;
                outbreak.DsVehicleHai            = command.Description;
                outbreak.CdModeTransmission      = command.TransmissionMode;
                outbreak.InFoodWater             = command.FoodOrWaterRelated;
                outbreak.InVehicleFw             = command.IsVehicleIdentified;
                outbreak.DsVehicleFw             = command.Vehicle;
                outbreak.InHealthcare            = command.HealthRelated;
                outbreak.CdVehicleIdentified     = command.CauseForOutbreak;
                outbreak.DsVehicleHai            = command.Description;
                outbreak.CdErDeptVisitsType      = command.EmergencyVisitsType;
                outbreak.AmErDeptVisits          = command.EmergencyVisits;
                outbreak.CdInpatientHosptialType = command.InpatientHospitalizationsType;
                outbreak.AmInpatientHospital     = command.InpatientHospitalizations;
                outbreak.AmDeaths     = command.Deaths;
                outbreak.CdDeathsType = command.DeathsType;



                outbreak.DtChdNotified  = command.NotifiedDate;
                outbreak.CdReporterType = command.FirstNotified;
                outbreak.NmReporter     = command.ReporterName ?? string.Empty;
                outbreak.DtInvestigated = command.InvestigationStarted;
                outbreak.DtClosed       = command.InvestigationClosed;

                outbreak.CdStatus = outbreak.DtClosed != null ? "CLOSED" : "OPEN";

                outbreak.CdSyndromes     = command.Syndrome;
                outbreak.DsSyndromeOther = command.OtherSyndrome;

                outbreak.DsDiseaseHazardOther = command.OtherDiseaseHazard;
                outbreak.AmEstimatedIll       = command.EstimatedNumber.GetValueOrDefault();
                outbreak.InInvestigated       = command.IsInvestigated;
                outbreak.InOutbreak           = command.IsOutbreak;


                outbreak.InRecommendations    = command.IsRecProvided;
                outbreak.CdRecommendationsHow = command.MethodofRec;

                //TODO:  this does not look correct
                outbreak.InImplemented    = command.WereRecommendationsImplemented;
                outbreak.InInternalAction = command.IsReportCompleted;


                outbreak.DtEarliestExposure   = command.FirstExposureDate;
                outbreak.DtLastExposure       = command.LastExposureDate;
                outbreak.DtEarliestOnset      = command.FirstOnsetDate;
                outbreak.DtLastOnset          = command.LastOnsetDate;
                outbreak.AmMedianDuration     = command.Duration;
                outbreak.CdMedianDurationUnit = command.TimeUnit;


                outbreak.InLabConfirmed = command.IsHumanSpecimens;
                outbreak.InLabConducted = command.IsLabTestingConducted;

                outbreak.AmLabConfirmed = (short?)command.NoOfCases;

                //TODO:  verify this does not look correct
                outbreak.InLabConfirmedFood = command.IsFoodSpecimens;

                outbreak.AmTotalCases    = command.TotalCases;
                outbreak.CdTotalCaseType = command.TotalCaseType;
                outbreak.AmNonStaffCases = command.NonStaffCases;
                outbreak.AmStaffCases    = command.StaffCases;
                outbreak.AmUnknownCases  = command.UnknownCases;

                if (!string.IsNullOrWhiteSpace(command.Comments))
                {
                    await CreateEvent(outbreak, OutbreakEventType.Review, command.Comments, eventDate);
                }

                if (outbreak.CdReviewStatus != command.ReviewStatus)
                {
                    outbreak.IdReviewer     = usernameProvider.GetUsername();
                    outbreak.DtReview       = DateTime.Now;
                    outbreak.CdReviewStatus = command.ReviewStatus;
                }

                await writeContext.SaveChangesAsync();

                transaction.Commit();
            }

            //save survey
            //NOTE:  This is not transacted with outbreak save
            //if can be, but it requires detecting a current pending transaction inside survey answer save
            if (command.SurveyUid != null)
            {
                await surveyService.Execute(new SaveSurveyAnswers
                {
                    OutbreakId = outbreak.IdOutbreak,
                    Answers    = command.SurveyAnswers,
                    SurveyId   = command.SurveyUid.Value
                });
            }
        }