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

                DataRow[] rowArray = new DataRow[dataSet.Count];
                dataSet.CopyTo(rowArray, 0);

                Array.ForEach(rowArray, row => {
                    var patId = row["PATIENTKEYID"].ToString();
                    if (mHelper.HasPatientMigrated(patId))
                    {
                        dataSet.Remove(row);
                    }
                });

                handler = new MeterReadingHandler(dataSet);

                handler.BGExtractionEvent           += BGExtractionEventHandler;
                handler.NutritionExtractionEvent    += NutritionExtractionEventHandler;
                handler.PumpDeliveryExtractionEvent += PumpDeliveryExtractionEventHandler;
                handler.PumpEventsExtractionEvent   += PumpEventsExtractionEventHandler;
                handler.UserSettingsExtractionEvent += UserSettingsExtractionEventHandler;
            }
            catch (Exception e)
            {
                throw new Exception("Error creating MeterReading mapping.", e);
            }
        }
        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);
            }
        }
예제 #3
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);
            }
        }
예제 #4
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);
            }
        }
예제 #5
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);
            }
        }
예제 #6
0
        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.");
            }
        }
        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);
            }
        }
예제 #8
0
        public void CreatePatientMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;
                //Guid instId = nHelper.GetInstitutionId(MigrationVariables.CurrentSiteId);

                foreach (DataRow row in dataSet)
                {
                    User user = new User();

                    // get userid from old aspnetdb matching on patientid #####.#####
                    // if no userid then create new one for this patient
                    var patId  = row["KEYID"].ToString();
                    var uid    = aHelper.GetUserIdFromPatientId(patId);
                    var userId = (uid != Guid.Empty) ? uid : Guid.NewGuid();
                    userId = nHelper.ValidGuid(userId);

                    if (mHelper.HasPatientMigrated(patId))
                    {
                        MappingStatistics.LogFailedMapping("PATIENTS", patId, "Patients", typeof(Patient), String.Empty, "Patient previously migrated.");
                        FailedCount++;
                    }
                    else
                    {
                        var medRecId = (row["MEDICALRECORDIDENTIFIER"] is DBNull) ? String.Empty : row["MEDICALRECORDIDENTIFIER"].ToString();

                        if (!String.IsNullOrEmpty(medRecId) && !medRecId.StartsWith("PR_"))
                        {
                            MemoryMappings.AddMRID(new MedicalRecordIdentifier {
                                MRID = medRecId,
                                //InstitutionId = instId,
                                PatientUserId = userId
                            });
                        }

                        var pat = new Patient
                        {
                            UserId      = userId,
                            Firstname   = (row["FIRSTNAME"] is DBNull) ? String.Empty : row["FIRSTNAME"].ToString(),
                            Lastname    = (row["LASTNAME"] is DBNull) ? String.Empty : row["LASTNAME"].ToString(),
                            Middlename  = (row["MIDDLENAME"] is DBNull) ? String.Empty : row["MIDDLENAME"].ToString(),
                            Gender      = (row["GENDER"] is DBNull) ? 1 : (row["GENDER"].ToString().ToLower().StartsWith("m", StringComparison.CurrentCulture)) ? 2 : 3, //From the GlobalStandards database, 'Gender' table
                            DateofBirth = (row["DOB"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["DOB"].ToString()),
                            Email       = (row["EMAIL"] is DBNull) ? String.Empty : row["EMAIL"].ToString(),
                            //InstitutionId = instId,
                            LastUpdatedByUser = userId
                        };

                        var adr = new PatientAddress
                        {
                            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(),
                            County            = (row["COUNTY"] is DBNull) ? String.Empty : row["COUNTY"].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 = userId
                        };

                        pat.PatientAddresses.Add(adr);

                        // must create clinipro user to store new userid for future usage
                        if (uid == Guid.Empty || uid != userId)
                        {
                            aHelper.CreateCliniProUser(userId, patId);

                            user.UserId = userId;
                            user.AssignedUserTypes.Add(new AssignedUserType {
                                UserId = userId, UserType = (int)UserType.Patient
                            });
                            user.CreationDate = DateTime.Now;

                            pat.User = user;
                        }

                        // add patient info to in-memery collection for use throughout application
                        MemoryMappings.AddPatientInfo(MigrationVariables.CurrentSiteId, patId, pat.UserId);

                        if (CanAddToContext(user.UserId))
                        {
                            CompletedMappings.Add(pat);
                        }
                        else
                        {
                            MappingStatistics.LogFailedMapping("PATIENTS", patId, "Patients", typeof(Patient), JsonConvert.SerializeObject(user), "Patient already exist in database.");
                            FailedCount++;
                        }
                    }
                }

                MappingStatistics.LogMappingStat("PATIENTS", RecordCount, "Patients", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating Patient mapping.", e);
            }
        }
예제 #9
0
        public void CreateDMDataMapping()
        {
            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 dm = new DiabetesManagementData
                            {
                                UserId         = userId,
                                LowBGLevel     = (row["LOWBGLEVEL"] is DBNull) ? 19 : (Int16)row["LOWBGLEVEL"],
                                HighBGLevel    = (row["HIGHBGLEVEL"] is DBNull) ? 201 : (Int16)row["HIGHBGLEVEL"],
                                PremealTarget  = (row["PREMEALTARGET"] is DBNull) ? 50 : (Int32)row["PREMEALTARGET"],
                                PostmealTarget = (row["POSTMEALTARGET"] is DBNull) ? 50 : (Int32)row["POSTMEALTARGET"],
                                ModifiedDate   = (row["LASTMODIFIEDDATE"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["LASTMODIFIEDDATE"].ToString()),
                                ModifiedUserId = (row["LASTMODIFIEDBYUSER"] is DBNull) ? Guid.Empty : mu.ParseGUID(row["LASTMODIFIEDBYUSER"].ToString())
                            };

                            // add to temp collection for addition with "PatientDevicesMapping"
                            MemoryMappings.AddDiabetesManagementData(dm);

                            var ibId = mu.FindInsulinBrandId(row["INSULINBRAND"].ToString());
                            var imId = mu.FindInsulinMethodId(row["INSULINMETHOD"].ToString());

                            CareSetting careset = new CareSetting();
                            careset.UserId                 = userId;
                            careset.HyperglycemicLevel     = (row["HYPERGLYCEMICLEVEL"] is DBNull) ? 0 : (Int16)row["HYPERGLYCEMICLEVEL"];
                            careset.HypoglycemicLevel      = (row["HYPOGLYCEMICLEVEL"] is DBNull) ? 0 : (Int16)row["HYPOGLYCEMICLEVEL"];
                            careset.InsulinMethod          = imId;
                            careset.InsulinBrand           = ibId;
                            careset.DiabetesManagementType = (row["DMTYPE"] is DBNull) ? String.Empty : row["DMTYPE"].ToString();
                            careset.DateModified           = (row["LASTMODIFIEDDATE"] is DBNull) ? new DateTime(1800, 1, 1) : mu.ParseFirebirdDateTime(row["LASTMODIFIEDDATE"].ToString());
                            careset.LastUpdatedByUser      = (row["LASTMODIFIEDBYUSER"] is DBNull) ? Guid.Empty : mu.ParseGUID(row["LASTMODIFIEDBYUSER"].ToString());

                            var ct = (row["DMCONTROLTYPE"] is DBNull) ? mu.ParseDMControlTypes(0) : mu.ParseDMControlTypes((Int32)row["DMCONTROLTYPE"]);
                            foreach (var item in ct)
                            {
                                DiabetesControlType dct = new DiabetesControlType();
                                dct.ControlName       = item.Key;
                                dct.DMDataId          = dm.DMDataId;
                                dct.IsEnabled         = (item.Value) ? true : false;
                                dct.LastUpdatedByUser = userId;

                                careset.DiabetesControlTypes.Add(dct);
                            }

                            if (CanAddToContext(careset.UserId, careset.HyperglycemicLevel, careset.HypoglycemicLevel))
                            {
                                CompletedMappings.Add(careset);
                            }
                            else
                            {
                                MappingStatistics.LogFailedMapping("DMDATA", patId, "CareSettings", typeof(CareSetting), JsonConvert.SerializeObject(careset), "Unable to add Care Setting to database.");
                                FailedCount++;
                            }
                        }
                    }
                }

                MappingStatistics.LogMappingStat("DMDATA", RecordCount, "CareSettings", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating CareSetting mapping.", e);
            }
        }
        public void CreatePumpSettingMapping()
        {
            try
            {
                var dataSet = TableAgent.DataSet.Tables[FbTableName].Rows;
                RecordCount = TableAgent.RowCount;
                var dateSetter = DateTime.Now;

                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);

                    var icDict = new Dictionary <char, ProgramTimeSlot> {
                        { '1', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '2', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '3', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '4', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '5', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '6', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '7', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '8', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } }
                    };

                    var bgDict = new Dictionary <char, ProgramTimeSlot> {
                        { '1', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '2', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '3', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '4', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '5', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '6', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '7', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '8', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } }
                    };

                    var bcDict = new Dictionary <char, ProgramTimeSlot> {
                        { '1', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '2', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '3', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '4', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '5', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '6', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '7', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '8', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } }
                    };

                    var cfDict = new Dictionary <char, ProgramTimeSlot> {
                        { '1', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '2', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '3', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '4', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '5', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '6', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '7', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } },
                        { '8', new ProgramTimeSlot {
                              DateSet = dateSetter
                          } }
                    };

                    PumpProgram icProgram = DefaultPumpProgram();
                    PumpProgram bgProgram = DefaultPumpProgram();
                    PumpProgram bcProgram = DefaultPumpProgram();
                    PumpProgram cfProgram = DefaultPumpProgram();

                    icProgram.ProgramName = "PROG_IC";
                    bgProgram.ProgramName = "PROG_BG";
                    bcProgram.ProgramName = "PROG_BGC";
                    cfProgram.ProgramName = "PROG_CF";

                    icProgram.ProgramTypeId = 4;
                    bgProgram.ProgramTypeId = 5;
                    bcProgram.ProgramTypeId = 7;
                    cfProgram.ProgramTypeId = 3;

                    icProgram.ProgramTimeSlots = new List <ProgramTimeSlot>();
                    bgProgram.ProgramTimeSlots = new List <ProgramTimeSlot>();
                    bcProgram.ProgramTimeSlots = new List <ProgramTimeSlot>();
                    cfProgram.ProgramTimeSlots = new List <ProgramTimeSlot>();

                    if (!mHelper.HasPatientMigrated(patId))
                    {
                        if (userId != Guid.Empty)
                        {
                            var tempList = new List <PumpSetting>();

                            // iterate through table columns and only get columns that are NOT time slots
                            // as these will be settings
                            for (int i = 0; i < row.Table.Columns.Count; i++)
                            {
                                var column = row.Table.Columns[i].ColumnName.Trim();
                                // don't want columns that start with these characters - these are timeslot values which are handled in the 'else' statement
                                var exclude = new List <bool> {
                                    column.StartsWith("ic", StringComparison.OrdinalIgnoreCase),
                                    column.StartsWith("cf", StringComparison.OrdinalIgnoreCase),
                                    column.StartsWith("target", StringComparison.OrdinalIgnoreCase),
                                    column.StartsWith("patientid", StringComparison.OrdinalIgnoreCase)
                                };

                                if (exclude.All(a => !a))
                                {
                                    PumpSetting ps = new PumpSetting();
                                    ps.SettingName  = column;
                                    ps.SettingValue = (row[column] is DBNull) ? String.Empty : row[column].ToString();
                                    ps.Date         = new DateTime(1800, 1, 1);

                                    tempList.Add(ps);

                                    if (CanAddToContext(ps.SettingValue))
                                    {
                                        CompletedMappings.Add(ps);
                                    }
                                    else
                                    {
                                        MappingStatistics.LogFailedMapping("INSULETPUMPSETTINGS", patId, "PumpSettings", typeof(PumpSetting), JsonConvert.SerializeObject(ps), "Pump Setting has no value.");
                                        FailedCount++;
                                    }
                                }
                                else
                                {
                                    if (!(row[column] is DBNull))
                                    {
                                        if (column.StartsWith("cf", StringComparison.OrdinalIgnoreCase) && cfDict.ContainsKey(column.Last()))
                                        {
                                            var cfd = cfDict[column.Last()];
                                            if (column.StartsWith("cfstart", StringComparison.OrdinalIgnoreCase))
                                            {
                                                cfd.StartTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                            }

                                            if (column.StartsWith("cfstop", StringComparison.OrdinalIgnoreCase))
                                            {
                                                cfd.StopTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                            }

                                            if (column.StartsWith("cfvalue", StringComparison.OrdinalIgnoreCase))
                                            {
                                                cfd.Value = mu.ParseDouble(row[column].ToString());
                                            }
                                        }

                                        if (column.StartsWith("ic", StringComparison.OrdinalIgnoreCase) && icDict.ContainsKey(column.Last()))
                                        {
                                            var icd = icDict[column.Last()];
                                            if (column.StartsWith("icstart", StringComparison.OrdinalIgnoreCase))
                                            {
                                                icd.StartTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                            }

                                            if (column.StartsWith("icstop", StringComparison.OrdinalIgnoreCase))
                                            {
                                                icd.StopTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                            }

                                            if (column.StartsWith("icvalue", StringComparison.OrdinalIgnoreCase))
                                            {
                                                icd.Value = mu.ParseDouble(row[column].ToString());
                                            }
                                        }

                                        if (column.StartsWith("target", StringComparison.OrdinalIgnoreCase) && bgDict.ContainsKey(column.Last()) && bcDict.ContainsKey(column.Last()))
                                        {
                                            var bgd = bgDict[column.Last()];
                                            var bcd = bcDict[column.Last()];

                                            if (column.StartsWith("targetbgstart", StringComparison.OrdinalIgnoreCase))
                                            {
                                                bgd.StartTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                                bcd.StartTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                            }

                                            if (column.StartsWith("targetbgstop", StringComparison.OrdinalIgnoreCase))
                                            {
                                                bgd.StopTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                                bcd.StopTime = mu.ParseFirebirdTimespan(row[column].ToString());
                                            }

                                            if (column.StartsWith("targetbg", StringComparison.OrdinalIgnoreCase))
                                            {
                                                bgd.Value = mu.ParseDouble(row[column].ToString());
                                            }

                                            if (column.StartsWith("targetbgcorrect", StringComparison.OrdinalIgnoreCase))
                                            {
                                                bcd.Value = mu.ParseDouble(row[column].ToString());
                                            }
                                        }
                                    }
                                }
                            }

                            // add to Memory Mappings so that Pump object and retieve
                            // a single user should only have a single collections of PumpSettings in the FB database
                            MemoryMappings.AddPumpSetting(userId, tempList);
                        }
                    }

                    //Purge dictionaries
                    PurgeDictionary(icDict);
                    PurgeDictionary(bgDict);
                    PurgeDictionary(bcDict);
                    PurgeDictionary(cfDict);

                    // add dictionary values (ProgramTimeSlots)
                    var icCollection = AddTimeSlots(icProgram.ProgramTimeSlots.ToList(), icDict.Values);
                    foreach (var item in icCollection)
                    {
                        icProgram.ProgramTimeSlots.Add(item);
                    }

                    var bgCollection = AddTimeSlots(bgProgram.ProgramTimeSlots.ToList(), bgDict.Values);
                    foreach (var item in bgCollection)
                    {
                        bgProgram.ProgramTimeSlots.Add(item);
                    }

                    var bcCollection = AddTimeSlots(bcProgram.ProgramTimeSlots.ToList(), bcDict.Values);
                    foreach (var item in bcCollection)
                    {
                        bcProgram.ProgramTimeSlots.Add(item);
                    }

                    var cfCollection = AddTimeSlots(cfProgram.ProgramTimeSlots.ToList(), cfDict.Values);
                    foreach (var item in cfCollection)
                    {
                        cfProgram.ProgramTimeSlots.Add(item);
                    }

                    // add pump programs to memory mappings
                    AddPumpProgram(userId, icProgram);
                    AddPumpProgram(userId, bgProgram);
                    AddPumpProgram(userId, bcProgram);
                    AddPumpProgram(userId, cfProgram);
                }

                MappingStatistics.LogMappingStat("INSULETPUMPSETTINGS", RecordCount, "PumpSettings", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating PumpSetting mapping.", e);
            }
        }
        public void CreatePumpTimeSlotsMapping()
        {
            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))
                    {
                        // temp collecions
                        var tempBasal = new List <ProgramTimeSlot>();
                        var tempBolus = new List <ProgramTimeSlot>();

                        var keyId       = mu.ParseInt(row["KEYID"].ToString());
                        var programKey  = mu.ParseInt(row["PROGRAMNUMBER"].ToString());
                        var programName = (row["PROGRAMNAME"] is DBNull) ? "Name" : row["PROGRAMNAME"].ToString();
                        var createDate  = (row["CREATEDATE"] is DBNull) ? DateTime.MinValue : mu.ParseFirebirdDateTime(row["CREATEDATE"].ToString());

                        for (int i = 1; i < 25; i++)
                        {
                            DateTime bastart = (row[$"BASAL{i}STARTTIME"] is DBNull) ? DateTime.MinValue : mu.ParseFirebirdDateTime(row[$"BASAL{i}STARTTIME"].ToString());
                            DateTime bastop  = (row[$"BASAL{i}STOPTIME"] is DBNull) ? DateTime.MinValue : mu.ParseFirebirdDateTime(row[$"BASAL{i}STOPTIME"].ToString());

                            if (bastart != DateTime.MinValue && bastop != DateTime.MinValue)
                            {
                                ProgramTimeSlot bats = new ProgramTimeSlot
                                {
                                    Value     = mu.ParseDouble(row[$"BASAL{i}VAL"].ToString()),
                                    StartTime = bastart.TimeOfDay,
                                    StopTime  = bastop.TimeOfDay,
                                    DateSet   = createDate
                                };

                                if (createDate != DateTime.MinValue && IsValid(bats))
                                {
                                    tempBasal.Add(bats);
                                }
                                else
                                {
                                    MappingStatistics.LogFailedMapping("PUMPTIMESLOTS", row["KEYID"].ToString(), "BasalProgramTimeSlots", typeof(ProgramTimeSlot), JsonConvert.SerializeObject(bats), "Unable to add BasalProgramTimeSlot to database because creation date was null.");
                                    FailedCount++;
                                }
                            }

                            if (i < 13)
                            {
                                DateTime botime = (row[$"BOLUS{i}TIME"] is DBNull) ? DateTime.MinValue : mu.ParseFirebirdDateTime(row[$"BOLUS{i}TIME"].ToString());

                                if (botime != DateTime.MinValue)
                                {
                                    ProgramTimeSlot bots = new ProgramTimeSlot
                                    {
                                        Value     = mu.ParseDouble(row[$"BOLUS{i}VAL"].ToString()),
                                        StartTime = botime.TimeOfDay,
                                        DateSet   = createDate
                                    };

                                    if (createDate != DateTime.MinValue && IsValid(bots))
                                    {
                                        tempBolus.Add(bots);
                                    }
                                    else
                                    {
                                        MappingStatistics.LogFailedMapping("PUMPTIMESLOTS", row["KEYID"].ToString(), "BolusProgramTimeSlots", typeof(ProgramTimeSlot), JsonConvert.SerializeObject(bots), "Unable to add BolusProgramTimeSlot to database because creation date was null.");
                                        FailedCount++;
                                    }
                                }
                            }
                        }

                        if (createDate == DateTime.MinValue)
                        {
                            FailedCount++;
                        }

                        Array.ForEach(tempBasal.ToArray(), a =>
                        {
                            MemoryMappings.AddBasalPrgTimeSlot(userId, createDate, a);
                        });

                        Array.ForEach(tempBolus.ToArray(), a =>
                        {
                            MemoryMappings.AddBolusPrgTimeSlot(userId, createDate, a);
                        });
                    }
                }

                MappingStatistics.LogMappingStat("PUMPTIMESLOTS", RecordCount, "BasalProgramTimeSlots", MemoryMappings.GetAllBasalPrgTimeSlots().Count, FailedCount);
                MappingStatistics.LogMappingStat("PUMPTIMESLOTS", RecordCount, "BolusProgramTimeSlots", MemoryMappings.GetAllBolusPrgTimeSlots().Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating Pump Program Time Slot mapping.", e);
            }
        }