public int GetInsuranceCompanyId(string companyKeyId)
        {
            var kv    = MemoryMappings.GetAllCompanies().Where(n => n.Key == companyKeyId).FirstOrDefault();
            var cName = db.InsuranceProviders.Where(n => n.Name == kv.Value).FirstOrDefault();

            return((cName == null) ? 0 : cName.CompanyId);
        }
        public SubscriptionHandler(Guid userId)
        {
            UserId = userId;

            nh            = new NumedicsGlobalHelpers();
            institutionId = MemoryMappings.GetAllInstitutions().Where(w => w.LegacySiteId == 20001).Select(s => s.InstitutionId).FirstOrDefault();// nh.GetInstitutionId(20001); // TODO: place in config file, because will change based on environment
        }
        public void GetInsuranceCompanyIdTest()
        {
            MemoryMappings.AddCompnay("12345", "Acme Insurance");

            Mock <DbSet <SQLDatabase.EF.InsuranceProvider> > moq_Ins = new Mock <DbSet <InsuranceProvider> >();

            moq_Ins.SetupData(new List <SQLDatabase.EF.InsuranceProvider>());

            var nIns = new InsuranceProvider
            {
                Name      = "Acme Insurance",
                IsActive  = true,
                CompanyId = 12345
            };

            moq_Ins.Object.Add(nIns);

            nuContext.Setup(c => c.InsuranceProviders).Returns(moq_Ins.Object);
            NumedicsGlobalHelpers nh = new NumedicsGlobalHelpers(nuContext.Object);

            // verify insurance id is returned
            Assert.AreEqual(nIns.CompanyId, nh.GetInsuranceCompanyId(nIns.CompanyId.ToString()));
            // verify 0 is returned for insurance providers not found
            Assert.IsTrue(nh.GetInsuranceCompanyId("99999").Equals(0));
        }
 private void AddPumpProgram(Guid userId, PumpProgram program)
 {
     if (program.ProgramTimeSlots != null || program.ProgramTimeSlots.Count > 0)
     {
         program.NumOfSegments = program.ProgramTimeSlots.Count;
         MemoryMappings.AddPumpProgram(userId, 0, program);
     }
 }
        private void ExtractTdd(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId  = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());

                    if (!keyId.Equals(Guid.Empty))
                    {
                        var bolus     = row["READINGNOTE"].ToString().Split().ElementAt(0).Split('=').LastOrDefault();
                        var bolusConf = row["READINGNOTE"].ToString().Split().ElementAt(1).Split('=').LastOrDefault();
                        var basal     = row["READINGNOTE"].ToString().Split().ElementAt(3).Split('=').LastOrDefault();
                        var basalConf = row["READINGNOTE"].ToString().Split().ElementAt(4).Split('=').LastOrDefault();
                        var total     = row["READINGNOTE"].ToString().Split().ElementAt(6).Split('=').LastOrDefault();

                        bool ptGood = Double.TryParse(total, out double pt);
                        bool puGood = Double.TryParse(bolus, out double pu);
                        bool paGood = Double.TryParse(basal, out double pa);

                        var td = new TotalDailyInsulinDelivery
                        {
                            TotalDelivered = (ptGood) ? pt : 0,
                            BasalDelivered = (paGood) ? pa : 0,
                            Suspended      = false,
                            TempActivated  = false,
                            Valid          = (string.Equals(bolusConf, "t", StringComparison.CurrentCultureIgnoreCase) && string.Equals(basalConf, "t", StringComparison.CurrentCultureIgnoreCase)) ? true : false,
                            BolusDelivered = (puGood) ? pu : 0,
                            Date           = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString()),
                            ReadingKeyId   = keyId,
                            UserId         = userId
                        };

                        TotalDailyInsulinDeliveries.Add(td);
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "TOTALDAILYINSULINDELIVERY", typeof(TotalDailyInsulinDelivery), String.Empty, "Failed to map TotalDailyInsulinDelivery reading, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
        public void AddDiabetesManagementDataTest()
        {
            //Arrange
            var dm = Builder <DiabetesManagementData> .CreateNew().Build();

            //Act
            MemoryMappings.AddDiabetesManagementData(dm);
            var getDm = MemoryMappings.GetAllDiabetesManagementData().FirstOrDefault(f => f.DMDataId == dm.DMDataId);

            //Assert
            Assert.IsNotNull(getDm);
        }
        private void btnNewMigration_Click(object sender, RoutedEventArgs e)
        {
            spCompletedMappngs.Visibility = Visibility.Hidden;
            spFailedMappings.Visibility   = Visibility.Hidden;
            spMigrationResults.Visibility = Visibility.Hidden;

            MappingStatistics.ClearAll();
            MemoryMappings.ClearAll();
            TableAgentCollection.TableAgents.Clear();

            Reset();
        }
        public void CreateInsurancePlansMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;

                foreach (DataRow row in dataSet)
                {
                    // get userid from old aspnetdb matching on patientid #####.#####
                    var patId  = (String)row["PATIENTID"].ToString();
                    var userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, patId);

                    if (userId != Guid.Empty)
                    {
                        var insp = new InsurancePlan
                        {
                            UserId            = userId,
                            PlanName          = String.Empty,
                            PlanType          = (row["INSTYPEID"] is DBNull) ? String.Empty : map.GetInsurancePlanType(row["INSTYPEID"].ToString()),
                            PlanIdentifier    = (row["PLANIDENTIFIER"] is DBNull) ? String.Empty : row["PLANIDENTIFIER"].ToString(),
                            PolicyNumber      = (row["POLICYNUMBER"] is DBNull) ? String.Empty : row["POLICYNUMBER"].ToString(),
                            GroupName         = (row["GROUPNAME"] is DBNull) ? String.Empty : row["GROUPNAME"].ToString(),
                            GroupIdentifier   = (row["GROUPNUMBER"] is DBNull) ? String.Empty : row["GROUPNUMBER"].ToString(),
                            CoPay             = (row["COPAY"] is DBNull) ? 0 : map.ParseMoney(row["COPAY"].ToString()),
                            Purchaser         = (row["PURCHASER"] is DBNull) ? String.Empty : row["PURCHASER"].ToString(),
                            IsActive          = (row["ISACTIVE"] is DBNull) ? false : map.ParseFirebirdBoolean(row["ISACTIVE"].ToString()),
                            InActiveDate      = (row["INACTIVEDATE"] is DBNull) ? new DateTime(1800, 1, 1) : map.ParseFirebirdDateTime(row["INACTIVEDATE"].ToString()),
                            EffectiveDate     = (row["EFFECTIVEDATE"] is DBNull) ? new DateTime(1800, 1, 1) : map.ParseFirebirdDateTime(row["EFFECTIVEDATE"].ToString()),
                            LastUpdatedByUser = userId
                        };

                        if (CanAddToContext(insp.UserId, insp.PlanType, insp.PolicyNumber))
                        {
                            tempCompanyId.Add(new Tuple <string, InsurancePlan>(row["INSCOID"].ToString(), insp));
                            CompletedMappings.Add(insp);
                        }
                        else
                        {
                            MappingStatistics.LogFailedMapping("INSURANCEPLANS2", row["KEYID"].ToString(), "InsurancePlans", typeof(InsurancePlan), JsonConvert.SerializeObject(insp), "Insurance Plan already exist in database.");
                            FailedCount++;
                        }
                    }
                }

                MappingStatistics.LogMappingStat("INSURANCEPLANS2", RecordCount, "InsurancePlans", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating InsurancePlan mapping.", e);
            }
        }
        public void GetAllDiabetesManagementDataTest()
        {
            //Arrange
            var dm = Builder <DiabetesManagementData> .CreateListOfSize(10).Build();

            //Act
            foreach (var d in dm)
            {
                MemoryMappings.AddDiabetesManagementData(d);
            }

            //Assert
            Assert.AreEqual(10, dm.Count);
        }
        public void CreatePatientPhoneNumbersMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;

                foreach (DataRow row in dataSet)
                {
                    // get userid from old aspnetdb matching on patientid #####.#####
                    var patId  = row["PARENTID"].ToString();
                    var userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, patId);

                    if (!mHelper.HasPatientMigrated(patId))
                    {
                        var patNum = new PatientPhoneNumber
                        {
                            UserId            = userId,
                            Number            = (row["NUMBER"] is DBNull) ? String.Empty : row["NUMBER"].ToString(),
                            Extension         = (row["EXTENSION"] is DBNull) ? String.Empty : row["EXTENSION"].ToString(),
                            Type              = (row["ATYPE"] is DBNull) ? 0 : map.ParseFirebirdPhoneTypes(row["ATYPE"].ToString()),
                            IsPrimary         = (row["ISPRIMARY"] is DBNull) ? false : map.ParseFirebirdBoolean(row["ISPRIMARY"].ToString()),
                            RecieveText       = (row["RECEIVETEXT"] is DBNull) ? false : map.ParseFirebirdBoolean(row["RECEIVETEXT"].ToString()),
                            LastUpdatedByUser = userId
                        };

                        if (userId != Guid.Empty && CanAddToContext(patNum.Number))
                        {
                            CompletedMappings.Add(patNum);
                        }
                        else
                        {
                            var fr = (userId == Guid.Empty) ? "Phone number has no corresponding patient." : "Patient phone number already exist in database.";

                            MappingStatistics.LogFailedMapping("PHONENUMBERS", row["KEYID"].ToString(), "PatientPhoneNumbers", typeof(PatientPhoneNumber), JsonConvert.SerializeObject(patNum), fr);
                            FailedCount++;
                        }
                    }
                }

                MappingStatistics.LogMappingStat("PHONENUMBERS", RecordCount, "PatientPhoneNumbers", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating PatientPhonenumber mapping.", e);
            }
        }
        private void ExtractTermBasal(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId  = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());

                    if (!keyId.Equals(Guid.Empty))
                    {
                        var bd = new BasalDelivery();
                        var dd = new BasalDeliveryData();

                        dd.Name  = "TERM_BASAL";
                        dd.Value = (row["READINGNOTE"] is DBNull) ? String.Empty : row["READINGNOTE"].ToString();
                        dd.Date  = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString());

                        bd.ReadingKeyId    = keyId;
                        bd.UserId          = userId;
                        bd.StartDateTime   = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString());
                        bd.AmountDelivered = 0;
                        bd.DeliveryRate    = 0;
                        bd.Duration        = String.Empty;
                        bd.IsTemp          = false;
                        bd.BasalDeliveryDatas.Add(dd);

                        BasalDeliveries.Add(bd);
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "BASALDELIVERY", typeof(BasalDelivery), String.Empty, "Failed to map TERM_BASAL reading, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
        private void ExtractBasal(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId  = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());

                    if (!keyId.Equals(Guid.Empty))
                    {
                        var value = (row["CLINIPROVALUE"] is DBNull) ? String.Empty : row["CLINIPROVALUE"].ToString();

                        bool ptGood = Double.TryParse(value, out double rate);

                        var bd = new BasalDelivery();

                        bd.ReadingKeyId    = keyId;
                        bd.UserId          = userId;
                        bd.StartDateTime   = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString());
                        bd.AmountDelivered = 0; // 0 means you must group times and multiple by rate programmaically
                        bd.DeliveryRate    = rate;
                        bd.Duration        = String.Empty;
                        bd.IsTemp          = false;

                        BasalDeliveries.Add(bd);
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "BASALDELIVERY", typeof(BasalDelivery), String.Empty, "Failed to map BASAL reading, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
Beispiel #13
0
        private ICollection <ProgramTimeSlot> GetBasalPrgTimeSlots(Guid userId, DateTime creationDate)
        {
            var slots = MemoryMappings.GetAllBasalPrgTimeSlots();
            ConcurrentBag <ProgramTimeSlot> results = new ConcurrentBag <ProgramTimeSlot>();

            if (slots.ContainsKey(userId))
            {
                var set = slots[userId];
                Array.ForEach(set.ToArray(), s => {
                    if (s.Key == creationDate)
                    {
                        Parallel.ForEach(s.Value.ToArray(), v => results.Add(v));
                    }
                });
            }

            return(results.ToList());
        }
        private void ExtractBg(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId  = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());

                    if (!keyId.Equals(Guid.Empty))
                    {
                        var bg = new BloodGlucoseReading
                        {
                            Active          = true,
                            ReadingDateTime = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString()),
                            ReadingKeyId    = keyId,
                            Units           = (row["METERUNITS"] is DBNull) ? String.Empty : row["METERUNITS"].ToString(),
                            Value           = (row["CLINIPROVALUE"] is DBNull) ? String.Empty : row["CLINIPROVALUE"].ToString(),
                            UserId          = userId,
                            IsCGMData       = false
                        };

                        BloodGlucoseReadings.Add(bg);
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "BLOODGLUCOSEREADING", typeof(BloodGlucoseReading), String.Empty, "Failed to map BG reading, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }

            OnBGExtractionEvent(new MeterReadingHandlerEventArgs(true));
        }
Beispiel #15
0
        public void SaveChanges()
        {
            try
            {
                var stats     = new SqlTableStats("Patients");
                var instStats = new SqlTableStats("Patients_Institutions");
                var addStats  = new SqlTableStats("PatientAddresses");

                Guid instId = nHelper.GetInstitutionId(MigrationVariables.CurrentSiteId);

                //save MRID collection
                var mrids = MemoryMappings.GetAllMRIDs();
                Array.ForEach(mrids.ToArray(), m => { m.InstitutionId = instId; });

                TransactionManager.DatabaseContext.MedicalRecordIdentifiers.AddRange(mrids);

                ////Set instition id for each patient
                var institution = TransactionManager.DatabaseContext.Institutions.FirstOrDefault(f => f.LegacySiteId == MigrationVariables.CurrentSiteId);
                Parallel.ForEach(CompletedMappings, c => { c.Institutions.Add(institution); c.InstitutionId = instId; });

                TransactionManager.DatabaseContext.Patients.AddRange(CompletedMappings);
                stats.PreSaveCount     = TransactionManager.DatabaseContext.ChangeTracker.Entries <Patient>().Where(w => w.State == System.Data.Entity.EntityState.Added).Count();
                instStats.PreSaveCount = stats.PreSaveCount;
                addStats.PreSaveCount  = TransactionManager.DatabaseContext.ChangeTracker.Entries <PatientAddress>().Where(w => w.State == System.Data.Entity.EntityState.Added).Count();

                var saved = TransactionManager.DatabaseContext.SaveChanges();
                stats.PostSaveCount     = (saved > stats.PreSaveCount) ? stats.PreSaveCount : saved;
                instStats.PostSaveCount = (saved > instStats.PreSaveCount) ? instStats.PreSaveCount : saved;
                addStats.PostSaveCount  = (saved > addStats.PreSaveCount) ? addStats.PreSaveCount : saved;

                MappingStatistics.SqlTableStatistics.Add(stats);
                MappingStatistics.SqlTableStatistics.Add(instStats);
                MappingStatistics.SqlTableStatistics.Add(addStats);
            }
            catch (DbEntityValidationException e)
            {
                throw new Exception("Error validating Patients entity", e);
            }
            catch (Exception e)
            {
                throw new Exception("Error saving Patients entity", e);
            }
        }
Beispiel #16
0
        private bool CanAddToContext(Guid userid, int subscriptionType, DateTime expiration, Guid institutionId)
        {
            if (institutionId == Guid.Empty)
            {
                return(false);
            }

            using (var ctx = new NuMedicsGlobalEntities())
            {
                if (MemoryMappings.GetAllInstitutions().Any(a => a.InstitutionId == institutionId))
                {
                    return(!ctx.Subscriptions.Any(a => a.UserId == userid && a.SubscriptionType == subscriptionType && a.ExpirationDate == expiration));
                }
                else
                {
                    return(false);
                }
            }
        }
        private void ExtractSettings(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId  = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());

                    if (!keyId.Equals(Guid.Empty))
                    {
                        var ds = new DeviceSetting
                        {
                            ReadingKeyId = keyId,
                            Name         = (row["EVENTSUBTYPE_1"] is DBNull) ? String.Empty : row["EVENTSUBTYPE_1"].ToString(),
                            Value        = (row["CLINIPROVALUE"] is DBNull) ? String.Empty : row["CLINIPROVALUE"].ToString(),
                            UserId       = userId,
                            ReadingDate  = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString())
                        };

                        DeviceSettings.Add(ds);
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "DEVICESETTINGS", typeof(DeviceSetting), String.Empty, "Failed to map User Setting reading, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }

            OnUserSettingsExtractionEvent(new MeterReadingHandlerEventArgs(true));
        }
Beispiel #18
0
        public void CreateTimeSlotsMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;

                foreach (DataRow row in TableAgent.DataSet.Tables[FbTableName].Rows)
                {
                    // get userid from old aspnetdb matching on patientid #####.#####
                    var patId  = row["PATIENTID"].ToString();
                    var userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, patId);

                    if (!mHelper.HasPatientMigrated(patId))
                    {
                        if (userId != Guid.Empty)
                        {
                            for (int i = 1; i < 9; i++)
                            {
                                DailyTimeSlot d = new DailyTimeSlot();
                                d.LastUpdatedByUser   = userId;
                                d.TimeSlotDescription = (row[$"SLOT{i}DESC"] is DBNull) ? String.Empty : row[$"SLOT{i}DESC"].ToString();
                                if (i < 8)
                                {
                                    d.TImeSlotBoundary = (row[$"SLOT{i}END"] is DBNull) ? new TimeSpan(12, 0, 0) : mu.ParseFirebirdTimespan(row[$"SLOT{i}END"].ToString());
                                }

                                tempMappings.Add(new Tuple <Guid, DailyTimeSlot>(userId, d));
                                CompletedMappings.Add(d);
                            }
                        }
                    }
                }

                MappingStatistics.LogMappingStat("TIMESLOT", RecordCount, "DailyTimeSlots", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error Creating TimeSlot mapping", e);
            }
        }
        public void SaveChanges()
        {
            try
            {
                // loop through mappings to assign clinicians to saved users
                Array.ForEach(CompletedMappings.ToArray(), c => {
                    User user  = nHelper.GetUser(c.UserId);
                    var siteId = MemoryMappings.GetSiteIdFromPatientInfo(c.UserId);
                    var instId = nHelper.GetInstitutionId(siteId);

                    if (instId != Guid.Empty)
                    {
                        c.InstitutionId = instId;

                        var usr       = TransactionManager.DatabaseContext.Users.Where(u => u.UserId == c.UserId).FirstOrDefault();
                        usr.Clinician = c;
                    }
                });

                var stats = new SqlTableStats
                {
                    Tablename    = "Clinicians",
                    PreSaveCount = CompletedMappings.Count()
                };

                stats.PreSaveCount = TransactionManager.DatabaseContext.ChangeTracker.Entries <Clinician>().Where(w => w.State == System.Data.Entity.EntityState.Added).Count();
                var saved = TransactionManager.DatabaseContext.SaveChanges();
                stats.PostSaveCount = (saved > stats.PreSaveCount) ? stats.PreSaveCount : saved;

                MappingStatistics.SqlTableStatistics.Add(stats);
            }
            catch (DbEntityValidationException e)
            {
                throw new Exception("Error validating Clinician entity", e);
            }
            catch (Exception e)
            {
                throw new Exception("Error saving Clinician entity", e);
            }
        }
        public void CreateInstitutionMapping()
        {
            try
            {
                var dataSet = aHelper.GetAllCorporationInfo();
                RecordCount = dataSet.Count;

                foreach (var ins in dataSet)
                {
                    var inst = new Institution
                    {
                        InstitutionId     = Guid.NewGuid(),
                        Name              = ins.Site_Name,
                        LegacySiteId      = (ins.SiteId.HasValue) ? ins.SiteId.Value : 0,
                        LastUpdatedByUser = Guid.Empty
                    };

                    MemoryMappings.AddInstitution(inst);

                    if (CanAddToContext(inst.Name, inst.LegacySiteId))
                    {
                        CompletedMappings.Add(inst);
                    }
                    else
                    {
                        MappingStatistics.LogFailedMapping("None", "None", "Institutions", typeof(Institution), JsonConvert.SerializeObject(inst), "Instition already exist in database.");
                        FailedCount++;
                    }
                }

                MappingStatistics.LogMappingStat("None", 0, "Institutions", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating Institution mapping.", e);
            }
        }
Beispiel #21
0
        public void CreateSubscriptionMapping()
        {
            try
            {
                var dataSet = MemoryMappings.GetAllUserIdsFromPatientInfo();
                RecordCount = dataSet.Count;

                foreach (var g in dataSet)
                {
                    var pats  = aHelper.GetAllPatientUsers();
                    var patId = pats.Where(w => w.UserId == g).Select(s => s.CliniProID).FirstOrDefault();
                    if (!mHelper.HasPatientMigrated(patId))
                    {
                        var sh = aHelper.GetSubscriptionInfo(g);

                        foreach (var sub in sh.GetMappedSubscriptions())
                        {
                            if (CanAddToContext(sub.UserId, sub.SubscriptionType, sub.ExpirationDate, sub.InstitutionId))
                            {
                                CompletedMappings.Add(sub);
                            }
                            else
                            {
                                MappingStatistics.LogFailedMapping("None", "None", "Subscriptions", typeof(Subscription), JsonConvert.SerializeObject(sub), "Subscription already exist in database.");
                                FailedCount++;
                            }
                        }
                    }
                }

                MappingStatistics.LogMappingStat("None", 0, "Subscriptions", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating Subscription mapping.", e);
            }
        }
Beispiel #22
0
        public void CreateNuLicenseMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;

                foreach (DataRow row in dataSet)
                {
                    var numed = row["LICENSETYPE"].ToString();

                    if (numed == "numedics")
                    {
                        var licenseCnt = (row["USERS"] is DBNull) ? 0 : (Int32)row["USERS"];
                        var expires    = (row["EXPIRES"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["EXPIRES"].ToString());

                        MemoryMappings.AddNuLicense(MigrationVariables.CurrentSiteId, licenseCnt, expires);
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error creating NuLicense mapping", e);
            }
        }
        public void LogMigration()
        {
            DateTime date = DateTime.Now;
            var      dh   = new DatabaseHistory {
                FbConnectionStringUsed = MigrationVariables.FbConnectionString,
                InstitutionName        = ahelper.GetAllCorporationInfo().Where(c => c.SiteId == MigrationVariables.CurrentSiteId).Select(s => s.Site_Name).FirstOrDefault(),
                LastMigrationDate      = date,
                MigrationLog           = MappingStatistics.ExportToLog(),
                SiteId = MigrationVariables.CurrentSiteId
            };

            Array.ForEach(MigrationVariables.FirebirdTableNames.ToArray(), t => {
                if (dh.TableHistories.Any(a => string.Equals(a.TableName, t, StringComparison.CurrentCultureIgnoreCase)))
                {
                    var th = dh.TableHistories.First(f => string.Equals(f.TableName, t, StringComparison.CurrentCultureIgnoreCase));
                    th.FirebirdRecordCount = +MappingStatistics.MappingStats.Where(w => string.Equals(w.FBTableName, t, StringComparison.CurrentCultureIgnoreCase)).Select(s => s.FBRecordCount).FirstOrDefault();
                    th.MigratedRecordCount = +MappingStatistics.MappingStats.Where(w => string.Equals(w.FBTableName, t, StringComparison.CurrentCultureIgnoreCase)).Select(s => s.CompletedMappingsCount).FirstOrDefault();
                }
                else
                {
                    dh.TableHistories.Add(new TableHistory
                    {
                        TableName           = t,
                        LastMigrationDate   = date,
                        FirebirdRecordCount = MappingStatistics.MappingStats.Where(w => string.Equals(w.FBTableName, t, StringComparison.CurrentCultureIgnoreCase)).Select(s => s.FBRecordCount).FirstOrDefault(),
                        MigratedRecordCount = MappingStatistics.MappingStats.Where(w => string.Equals(w.FBTableName, t, StringComparison.CurrentCultureIgnoreCase)).Select(s => s.CompletedMappingsCount).FirstOrDefault()
                    });
                }
            });

            Array.ForEach(TransactionManager.DatabaseContext.Patients.ToArray(), p => {
                var pat = MemoryMappings.GetAllPatientInfo().FirstOrDefault(f => f.Item3 == p.UserId);
                if (pat != null)
                {
                    dh.PatientHistories.Add(new PatientHistory
                    {
                        BirthDate         = p.DateofBirth,
                        FirebirdPatientId = pat.Item2,
                        Firstname         = p.Firstname,
                        Lastname          = p.Lastname,
                        SqlUserId         = pat.Item3,
                        MigrationDate     = date,
                    });
                }
            });

            Array.ForEach(TransactionManager.DatabaseContext.UserAuthentications.ToArray(), p =>
            {
                var userInfo = ahelper.GetAspUserInfo(p.Username);
                Guid legId   = (userInfo == null) ? Guid.Empty : userInfo.UserId;

                dh.UserHistories.Add(new UserHistory
                {
                    SqlUserId     = p.UserId,
                    MigrationDate = date,
                    Username      = p.Username,
                    LegacyUserId  = legId
                });
            });

            AddDatabaseMigration(dh);
        }
Beispiel #24
0
        public void CreatePumpProgramsMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;

                foreach (DataRow row in dataSet)
                {
                    // get userid from old aspnetdb matching on patientid #####.#####
                    var patId  = row["PATIENTID"].ToString();
                    var userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, patId);

                    if (!mHelper.HasPatientMigrated(patId))
                    {
                        if (userId != Guid.Empty)
                        {
                            var CreationDate = (row["CREATEDATE"] is DBNull) ? DateTime.MinValue : mu.ParseFirebirdDateTime(row["CREATEDATE"].ToString());
                            var Source       = (row["SOURCE"] is DBNull) ? String.Empty : row["SOURCE"].ToString();
                            var Valid        = mu.ParseFirebirdBoolean(row["ACTIVEPROGRAM"].ToString());

                            for (int i = 1; i < 8; i++)
                            {
                                var pKey = (row[$"PROG{i}KEYID"] is DBNull) ? 0 : mu.ParseInt(row[$"PROG{i}KEYID"].ToString());

                                if (pKey != 0)
                                {
                                    for (int s = 0; s < 1; s++)
                                    {
                                        PumpProgram p = new PumpProgram();

                                        p.CreationDate  = CreationDate;
                                        p.Source        = Source;
                                        p.Valid         = true;
                                        p.IsEnabled     = Valid;
                                        p.ProgramKey    = pKey;
                                        p.NumOfSegments = 7;
                                        p.ProgramName   = $"Prog {pKey}";

                                        if (s == 0)
                                        {
                                            p.ProgramTypeId    = 1;
                                            p.ProgramTimeSlots = GetBasalPrgTimeSlots(userId, CreationDate);
                                        }

                                        if (s == 1)
                                        {
                                            p.ProgramTypeId    = 2;
                                            p.ProgramTimeSlots = GetBolusPrgTimeSlots(userId, CreationDate);
                                        }

                                        if (CreationDate != DateTime.MinValue && pKey != 0 && p.ProgramTimeSlots.Count > 0)
                                        {
                                            MemoryMappings.AddPumpProgram(userId, pKey, p);
                                        }
                                        else
                                        {
                                            MappingStatistics.LogFailedMapping("PATIENTPUMPPROGRAM", row["KEYID"].ToString(), "PumpPrograms", typeof(PumpProgram), JsonConvert.SerializeObject(p), "Unable to add PumpProgram to database because creation date was null.");
                                            FailedCount++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                MappingStatistics.LogMappingStat("PATIENTPUMPPROGRAM", RecordCount, "PumpPrograms", MemoryMappings.GetAllPumpPrograms().Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating PumpProgram mapping.", e);
            }
        }
        public void CreatePumpsMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;

                foreach (DataRow row in dataSet)
                {
                    // get userid from old aspnetdb matching on patientid #####.#####
                    var patId  = row["PATIENTID"].ToString();
                    var userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, patId);

                    if (!mHelper.HasPatientMigrated(patId))
                    {
                        if (userId != Guid.Empty)
                        {
                            List <PumpSetting> settings = null;
                            List <PumpProgram> programs = null;

                            if (MemoryMappings.GetAllPumpSettings().ContainsKey(userId))
                            {
                                var set = MemoryMappings.GetAllPumpSettings().Where(k => k.Key == userId).Single();
                                settings = set.Value;
                            }

                            if (MemoryMappings.GetAllPumpPrograms().ContainsKey(userId))
                            {
                                var allprog = MemoryMappings.GetAllPumpPrograms().Count; //TESTING

                                var prog = MemoryMappings.GetAllPumpPrograms().Where(p => p.Key == userId).Single();
                                var tl   = prog.Value;
                                programs = new List <PumpProgram>();
                                Array.ForEach(tl.ToArray(), a => {
                                    if (a.Item2.ProgramTimeSlots.Count > 0)
                                    {
                                        programs.Add(a.Item2);
                                    }
                                });
                            }

                            var pum = new Pump
                            {
                                UserId          = userId,
                                PumpType        = "Meter",
                                PumpName        = (row["PUMPBRAND"] is DBNull) ? String.Empty : row["PUMPBRAND"].ToString(),
                                PumpStartDate   = mu.ParseFirebirdDateTime(row["PUMPSTARTDATE"].ToString()),
                                PumpInfusionSet = (row["PUMPINFUSIONSET"] is DBNull) ? String.Empty : row["PUMPINFUSIONSET"].ToString(),
                                Cannula         = mu.ParseDouble(row["CANNULA"].ToString()),
                                ReplacementDate = mu.ParseFirebirdDateTime(row["DATEREPLACED"].ToString()),
                                Notes           = (row["NOTES"] is DBNull) ? String.Empty : row["NOTES"].ToString(),
                                PumpSettings    = settings,
                                PumpPrograms    = programs
                            };

                            MemoryMappings.AddPump(pum);

                            if (CanAddToContext(pum.UserId, pum.PumpName))
                            {
                                CompletedMappings.Add(pum);
                            }
                            else
                            {
                                MappingStatistics.LogFailedMapping("PATIENTPUMP", patId, "Pumps", typeof(Pump), JsonConvert.SerializeObject(pum), "Unable to add Pump to database.");
                                FailedCount++;
                            }
                        }
                    }
                }

                MappingStatistics.LogMappingStat("PATIENTPUMP", RecordCount, "Pumps", CompletedMappings.Count, FailedCount);
            }
            catch (Exception)
            {
                throw new Exception("Error creating Pump mapping.");
            }
        }
        private void ExtractNutrition(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId          = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId         = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());
                    string eventSubType = (row["EVENTSUBTYPE_1"] is DBNull) ? String.Empty : row["EVENTSUBTYPE_1"].ToString();

                    if (!keyId.Equals(Guid.Empty))
                    {
                        var date = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString());

                        var nt = new NutritionReading
                        {
                            Date            = date,
                            ReadingDateTime = date,
                            ReadingKeyId    = keyId,
                            UserId          = userId
                        };

                        bool canAdd = true;
                        var cpValue = (row["CLINIPROVALUE"] is DBNull) ? 0 : mu.ParseDouble(row["CLINIPROVALUE"].ToString());

                        switch (eventSubType)
                        {
                        case "NUT_CARBS":
                            nt.Carbohydrates = cpValue;
                            break;

                        case "NUT_FAT":
                            nt.Fat = cpValue;
                            break;

                        case "NUT_CAL":
                            nt.Calories = cpValue;
                            break;

                        case "NUT_PROT":
                            nt.Protien = cpValue;
                            break;

                        default:
                            canAdd = false;
                            NoReadingTypeMatch(row);
                            break;
                        }

                        if (canAdd)
                        {
                            NutritionReadings.Add(nt);
                        }
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "NUTRITIONREADINGS", typeof(NutritionReading), String.Empty, "Failed to map nutrition reading, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }

            OnNutritionExtractionEvent(new MeterReadingHandlerEventArgs(true));
        }
        private void ExtractPumpEvents(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId           = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId          = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());
                    string eventSubType1 = (row["EVENTSUBTYPE_1"] is DBNull) ? String.Empty : row["EVENTSUBTYPE_1"].ToString();

                    if (!keyId.Equals(Guid.Empty))
                    {
                        var pe = new ReadingEvent
                        {
                            EventTime    = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString()),
                            ReadingKeyId = keyId,
                            EventValue   = (row["CLINIPROVALUE"] is DBNull) ? String.Empty : row["CLINIPROVALUE"].ToString(),
                            UserId       = userId,
                            StartTime    = new DateTime(1800, 1, 1),
                            StopTime     = new DateTime(1800, 1, 1),
                            ResumeTime   = new DateTime(1800, 1, 1)
                        };

                        switch (eventSubType1.ToLower())
                        {
                        case "activate":
                            pe.EventType = (int)ReadingEventType.Activate;
                            break;

                        case "date_change":
                            pe.EventType = (int)ReadingEventType.DateChange;
                            break;

                        case "deactivate":
                            pe.EventType = (int)ReadingEventType.Deactivate;
                            break;

                        case "remote_hazard":
                            pe.EventType = (int)ReadingEventType.RemoteHazard;
                            break;

                        case "hist_alarm":
                            pe.EventType = (int)ReadingEventType.AlarmHistory;
                            break;

                        case "download":
                            pe.EventType = (int)ReadingEventType.Download;
                            break;

                        case "occlusion":
                            pe.EventType = (int)ReadingEventType.Occlusion;
                            break;

                        case "pump_advise":
                            pe.EventType = (int)ReadingEventType.PumpAdvise;
                            break;

                        case "pump_hazard":
                            pe.EventType = (int)ReadingEventType.PumpHazard;
                            break;

                        case "time_adjust":
                            pe.EventType = (int)ReadingEventType.TimeChange;
                            break;

                        case "suspended":
                            pe.EventType = (int)ReadingEventType.Suspend;
                            break;

                        case "resume":
                            pe.EventType = (int)ReadingEventType.Resume;
                            break;

                        default:
                            pe.EventType = 0;
                            break;
                        }

                        ReadingEvents.Add(pe);
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "READINGEVENT", typeof(ReadingEvent), String.Empty, "Failed to map reading event, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }

            OnPumpEventsExtractionEvent(new MeterReadingHandlerEventArgs(true));
        }
        private void ExtractBolus(ICollection <DataRow> rows)
        {
            var exceptions = new ConcurrentQueue <Exception>();

            Parallel.ForEach(rows, (row) => {
                try
                {
                    Guid keyId    = MemoryMappings.GetReadingHeaderKeyId(row["DOWNLOADKEYID"].ToString());
                    Guid userId   = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, row["PATIENTKEYID"].ToString());
                    DateTime date = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString());

                    if (!keyId.Equals(Guid.Empty))
                    {
                        Dictionary <string, string> bolusData = GetBolusData(row["METERSENT"].ToString());


                        var carb = new BolusCarb
                        {
                            Date      = date,
                            CarbValue = mu.ParseInt(bolusData["Carbs"])
                        };

                        var bgTar = new BGTarget
                        {
                            Date     = date,
                            TargetBG = mu.ParseInt(bolusData["Target BG"])
                        };

                        var ic = new InsulinCarbRatio
                        {
                            Date    = date,
                            ICRatio = mu.ParseInt(bolusData["IC Ratio"])
                        };

                        var cf = new CorrectionFactor
                        {
                            Date = date,
                            CorrectionFactorValue = mu.ParseInt(bolusData["Correct"])
                        };

                        var iCorr = new InsulinCorrection
                        {
                            Date = date,
                            InsulinCorrectionValue = mu.ParseInt(bolusData["Correction"]),
                            InsulinCorrectionAbove = mu.ParseInt(bolusData["Correction Above"])
                        };

                        var bd = new BolusDelivery();

                        double dCarbs = mu.ParseDouble(bolusData["Carbs"]);
                        double dIC    = mu.ParseDouble(bolusData["IC Ratio"]);

                        bd.ReadingKeyId    = keyId;
                        bd.UserId          = userId;
                        bd.StartDateTime   = (row["READINGDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["READINGDATETIME"].ToString());
                        bd.AmountDelivered = mu.ParseDouble(bolusData["Total"]);
                        bd.AmountSuggested = (dCarbs == 0.0) ? 0.0 : (dCarbs / dIC);
                        bd.Duration        = mu.ParseInt(bolusData["Extended Duration"]);
                        bd.Type            = "BolusDeliveryData";


                        bolusData.Remove("Carbs");
                        bolusData.Remove("Target BG");
                        bolusData.Remove("IC Ratio");
                        bolusData.Remove("Correct");
                        bolusData.Remove("Correction");
                        bolusData.Remove("Correct Above");
                        for (int i = 0; i < bolusData.Count; i++)
                        {
                            bd.BolusDeliveryDatas.Add(new BolusDeliveryData
                            {
                                Date  = date,
                                Name  = bolusData.ElementAt(i).Key,
                                Value = (String.IsNullOrEmpty(bolusData.ElementAt(i).Value)) ? String.Empty : bolusData.ElementAt(i).Value.Trim()
                            });
                        }

                        bd.BGTarget          = bgTar;
                        bd.BolusCarb         = carb;
                        bd.InsulinCarbRatio  = ic;
                        bd.InsulinCorrection = iCorr;
                        bd.CorrectionFactor  = cf;

                        BolusDeliveries.Add(bd);
                    }
                    else
                    {
                        var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";
                        MappingStatistics.LogFailedMapping("METERREADING", primeKey, "BOLUSDELIVERY", typeof(BolusDelivery), String.Empty, "Failed to map BOLUS reading, unable to parse key id.");
                    }
                }
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            });

            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
        public void CreateDeviceMeterReadingHeaderMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;

                foreach (DataRow row in dataSet)
                {
                    // get userid from old aspnetdb matching on patientid #####.#####
                    var patId  = row["PATIENTKEYID"].ToString();
                    var userId = MemoryMappings.GetUserIdFromPatientInfo(MigrationVariables.CurrentSiteId, patId);

                    if (!mHelper.HasPatientMigrated(patId))
                    {
                        if (userId != Guid.Empty)
                        {
                            var dmData    = MemoryMappings.GetAllDiabetesManagementData().Where(w => w.UserId == userId).FirstOrDefault();
                            var meterName = (row["METERNAME"] is DBNull) ? String.Empty : row["METERNAME"].ToString();

                            var dev = new PatientDevice
                            {
                                UserId          = userId,
                                MeterIndex      = (row["NUMEDICSMETERINDEX"] is DBNull) ? 0 : (Int32)row["NUMEDICSMETERINDEX"],
                                Manufacturer    = (row["MANUFACTURER"] is DBNull) ? String.Empty : row["MANUFACTURER"].ToString(),
                                DeviceModel     = (row["METERMODEL"] is DBNull) ? String.Empty : row["METERMODEL"].ToString(),
                                DeviceName      = meterName,
                                SerialNumber    = (row["SERIALNUMBER"] is DBNull) ? string.Empty : row["SERIALNUMBER"].ToString(),
                                SoftwareVersion = (row["SOFTWAREVERSION"] is DBNull) ? String.Empty : row["SOFTWAREVERSION"].ToString(),
                                HardwareVersion = (row["HARDWAREVERSION"] is DBNull) ? String.Empty : row["HARDWAREVERSION"].ToString()
                            };

                            if (dmData != null)
                            {
                                dev.DiabetesManagementData = dmData;
                            }

                            var mrh = new ReadingHeader
                            {
                                ReadingKeyId        = Guid.NewGuid(),
                                UserId              = userId,
                                LegacyDownloadKeyId = (row["DOWNLOADKEYID"] is DBNull) ? String.Empty : row["DOWNLOADKEYID"].ToString(),
                                ServerDateTime      = (row["SERVERDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["SERVERDATETIME"].ToString()),
                                MeterDateTime       = (row["METERDATETIME"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["METERDATETIME"].ToString()),
                                Readings            = (row["READINGS"] is DBNull) ? 0 : (Int32)row["READINGS"],
                                SiteSource          = (row["SOURCE"] is DBNull) ? String.Empty : row["SOURCE"].ToString(),
                                ReviewedOn          = (row["REVIEWEDON"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["REVIEWEDON"].ToString()),
                            };

                            if (meterName.ToLower().Contains("omnipod"))
                            {
                                var ePump = MemoryMappings.GetAllPump().Where(w => w.UserId == userId).FirstOrDefault();

                                if (ePump != null)
                                {
                                    mrh.Pump           = new Pump();
                                    mrh.Pump.PumpKeyId = mrh.ReadingKeyId;

                                    if (ePump.PumpPrograms != null)
                                    {
                                        mrh.Pump.PumpPrograms = new List <PumpProgram>();
                                        Array.ForEach(ePump.PumpPrograms.ToArray(), p =>
                                        {
                                            var prog = new PumpProgram
                                            {
                                                CreationDate  = p.CreationDate,
                                                NumOfSegments = p.NumOfSegments,
                                                ProgramKey    = p.ProgramKey,
                                                ProgramName   = p.ProgramName,
                                                Source        = p.Source,
                                                Valid         = p.Valid,
                                                PumpKeyId     = mrh.Pump.PumpKeyId,
                                                IsEnabled     = p.IsEnabled,
                                                ProgramTypeId = p.ProgramTypeId
                                            };

                                            if (p.ProgramTimeSlots != null && p.ProgramTimeSlots.Count != 0)
                                            {
                                                Array.ForEach(p.ProgramTimeSlots.ToArray(), a =>
                                                {
                                                    prog.ProgramTimeSlots.Add(a);
                                                });
                                            }

                                            CompletedPumpProgramMappings.Add(prog);

                                            //if (p.BolusProgramTimeSlots != null && p.BolusProgramTimeSlots.Count != 0)
                                            //{
                                            //    Array.ForEach(p.BolusProgramTimeSlots.ToArray(), r =>
                                            //    {
                                            //        prog.BolusProgramTimeSlots.Add(r);
                                            //    });
                                            //}
                                        });
                                    }

                                    if (ePump.PumpSettings != null)
                                    {
                                        mrh.Pump.PumpSettings = new List <PumpSetting>();
                                        Array.ForEach(ePump.PumpSettings.ToArray(), s =>
                                        {
                                            var ps = new PumpSetting
                                            {
                                                Date         = s.Date,
                                                Description  = s.Description,
                                                SettingName  = s.SettingName,
                                                SettingValue = s.SettingValue,
                                                PumpKeyId    = mrh.Pump.PumpKeyId
                                            };

                                            CompletedPumpSettingMappings.Add(ps);
                                        });
                                    }

                                    mrh.Pump.ActiveProgramId = ePump.ActiveProgramId;
                                    mrh.Pump.Cannula         = ePump.Cannula;
                                    mrh.Pump.Notes           = ePump.Notes;
                                    mrh.Pump.PumpInfusionSet = ePump.PumpInfusionSet;
                                    mrh.Pump.PumpName        = ePump.PumpName;
                                    mrh.Pump.PumpStartDate   = ePump.PumpStartDate;
                                    mrh.Pump.PumpType        = ePump.PumpType;
                                    mrh.Pump.ReplacementDate = ePump.ReplacementDate;
                                    mrh.Pump.UserId          = ePump.UserId;
                                }
                            }

                            bool alreadyMapped = false;

                            if (CompletedMappings.Any(a => a.SerialNumber == dev.SerialNumber))
                            {
                                alreadyMapped = true;

                                var device = CompletedMappings.Where(w => w.SerialNumber == dev.SerialNumber).FirstOrDefault();
                                device.ReadingHeaders.Add(mrh);
                            }
                            else
                            {
                                dev.ReadingHeaders.Add(mrh);
                            }

                            if (CanAddToContext(dev.UserId, dev.SerialNumber) && !alreadyMapped)
                            {
                                if (!CompletedMappings.Any(a => a.SerialNumber == dev.SerialNumber))
                                {
                                    CompletedMappings.Add(dev);
                                }

                                MemoryMappings.AddReadingHeaderkeyId(mrh.LegacyDownloadKeyId.Trim(), mrh.ReadingKeyId);
                            }
                            else
                            {
                                if (alreadyMapped && !String.IsNullOrEmpty(dev.SerialNumber))
                                {
                                    MemoryMappings.AddReadingHeaderkeyId(mrh.LegacyDownloadKeyId.Trim(), mrh.ReadingKeyId);
                                }

                                var fr = (dev.UserId == Guid.Empty) ? "Device has no corresponding user." : (String.IsNullOrEmpty(dev.SerialNumber)) ? "Device has no serial number recorded." : "Device already assigned to user.";

                                MappingStatistics.LogFailedMapping("METERREADERHEADER", row["DOWNLOADKEYID"].ToString(), "PatientDevices", typeof(PatientDevice), JsonConvert.SerializeObject(dev), fr);
                                FailedCount++;
                            }
                        }
                    }
                }

                MappingStatistics.LogMappingStat("METERREADINGHEADER", RecordCount, "PatientDevices", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating Patient Device (MeterReadingHeader) mapping.", e);
            }
        }
Beispiel #30
0
        public void CreateInsuranceCompanyMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;

                foreach (DataRow row in dataSet)
                {
                    if (!String.IsNullOrEmpty(row["NAME"].ToString()))
                    {
                        var name = row["NAME"].ToString();
                        var kId  = row["KEYID"].ToString();

                        MemoryMappings.AddCompnay(kId, name);

                        var ips = new InsuranceProvider
                        {
                            Name              = name,
                            IsActive          = map.ParseFirebirdBoolean(row["ISACTIVE"].ToString()),
                            InActiveDate      = map.ParseFirebirdDateTime(row["INACTIVEDATE"].ToString()),
                            LastUpdatedByUser = Guid.Empty
                        };

                        var adr = new InsuranceAddress
                        {
                            Street1           = (row["STREET1"] is DBNull) ? String.Empty : row["STREET1"].ToString(),
                            Street2           = (row["STREET2"] is DBNull) ? String.Empty : row["STREET2"].ToString(),
                            Street3           = (row["STREET3"] is DBNull) ? String.Empty : row["STREET3"].ToString(),
                            City              = (row["CITY"] is DBNull) ? String.Empty : row["CITY"].ToString(),
                            State             = (row["STATE"] is DBNull) ? String.Empty : row["STATE"].ToString(),
                            Zip               = (row["ZIP"] is DBNull) ? String.Empty : row["ZIP"].ToString(),
                            Country           = (row["COUNTRY"] is DBNull) ? String.Empty : row["COUNTRY"].ToString(),
                            LastUpdatedByUser = Guid.Empty
                        };

                        var cont = new InsuranceContact
                        {
                            FullName          = (row["CONTACTNAME"] is DBNull) ? "No Name" : row["CONTACTNAME"].ToString(),
                            Email             = (row["EMAIL"] is DBNull) ? String.Empty : row["EMAIL"].ToString(),
                            LastUpdatedByUser = Guid.Empty
                        };

                        ips.InsuranceAddresses.Add(adr);
                        ips.InsuranceContacts.Add(cont);

                        if (CanAddToContext(ips.Name))
                        {
                            CompletedMappings.Add(ips);
                        }
                        else
                        {
                            MappingStatistics.LogFailedMapping("INSURANCECOS", kId, "InsuranceProviders", typeof(InsuranceProvider), JsonConvert.SerializeObject(ips), "Insurance Provider already exist in database.");
                            FailedCount++;
                        }
                    }
                }

                MappingStatistics.LogMappingStat("INSURANCECOS", RecordCount, "InsuranceProviders", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating InsuranceProvider mapping.", e);
            }
        }