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);
            }
        }
        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 CreateClinicianMapping()
        {
            try
            {
                var dataSet = aHelper.GetAllAdminsUsers().Where(w => w.CPSiteId == MigrationVariables.CurrentSiteId).ToList();
                RecordCount = dataSet.Count;

                foreach (var adUser in dataSet)
                {
                    var userInfo = aHelper.GetAspUserInfo(adUser.UserId);
                    if (mHelper.HasUserMigrated((userInfo == null) ? String.Empty : userInfo.UserName, adUser.UserId))
                    {
                        MappingStatistics.LogFailedMapping("None", "None", "Clinicians", typeof(Clinician), String.Empty, "Clinician previously migrated.");
                        FailedCount++;
                    }
                    else
                    {
                        var clin = new Clinician
                        {
                            UserId             = nHelper.ValidGuid(adUser.UserId),
                            Firstname          = "No Name",
                            Lastname           = "No Name",
                            StateLicenseNumber = "No License Number",
                            Email                = "",
                            InstitutionId        = nHelper.GetInstitutionId(MigrationVariables.CurrentSiteId),
                            InstitutionAddressId = 0//nHelper.GetInstitutionAddressId(MigrationVariables.CurrentSiteId),
                        };

                        clin.LastUpdatedByUser = clin.UserId;

                        if (CanAddToContext(clin.UserId))
                        {
                            CompletedMappings.Add(clin);
                        }
                        else
                        {
                            MappingStatistics.LogFailedMapping("None", "None", "Clinicians", typeof(Clinician), JsonConvert.SerializeObject(clin), "Clinician already exist in database.");
                            FailedCount++;
                        }
                    }
                }

                MappingStatistics.LogMappingStat("None", 0, "Clinicians", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating Clinician mapping.", e);
            }
        }
        private void BGExtractionEventHandler(object sender, CustomEvents.MeterReadingHandlerEventArgs e)
        {
            if (handler != null && e.ExtractionSuccessful)
            {
                CompletedBGMappings.AddRange(handler.BloodGlucoseReadings);
                var fc = MappingStatistics.FailedMappingCollection.Where(w => w.ObjectType == typeof(BloodGlucoseReading)).Count();
                MappingStatistics.LogMappingStat("METERREADING", RecordCount, "BloodGlucoseReadings", CompletedBGMappings.Count, fc);

                BgExtractionComplete = true;
            }
            else
            {
                BgExtractionComplete = true;
                throw new Exception($"Extraction incomplete for {e.ExtractionName}");
            }
        }
        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);
            }
        }
        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 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);
            }
        }
        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));
        }
        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));
        }
Пример #11
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);
            }
        }
Пример #12
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);
            }
        }
        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);
            }
        }
        private void PumpDeliveryExtractionEventHandler(object sender, CustomEvents.MeterReadingHandlerEventArgs e)
        {
            if (handler != null && e.ExtractionSuccessful)
            {
                CompletedBolusMappings.AddRange(handler.BolusDeliveries);
                CompletedBasalMappings.AddRange(handler.BasalDeliveries);
                CompletedTDDMappings.AddRange(handler.TotalDailyInsulinDeliveries);

                var fcBol = MappingStatistics.FailedMappingCollection.Where(w => w.ObjectType == typeof(BolusDelivery)).Count();
                var fcBas = MappingStatistics.FailedMappingCollection.Where(w => w.ObjectType == typeof(BasalDelivery)).Count();
                var fcTdd = MappingStatistics.FailedMappingCollection.Where(w => w.ObjectType == typeof(TotalDailyInsulinDelivery)).Count();

                MappingStatistics.LogMappingStat("METERREADING", RecordCount, "BolusDelivery", CompletedBolusMappings.Count, fcBol);
                MappingStatistics.LogMappingStat("METERREADING", RecordCount, "BasalDelivery", CompletedBasalMappings.Count, fcBas);
                MappingStatistics.LogMappingStat("METERREADING", RecordCount, "TotalDailyInsulinDeliveries", CompletedTDDMappings.Count, fcTdd);

                PumpDeliveryExtractionComplete = true;
            }
            else
            {
                PumpDeliveryExtractionComplete = true;
                throw new Exception($"Extraction incomplete for {e.ExtractionName}");
            }
        }
        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);
            }
        }
Пример #16
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.");
            }
        }
Пример #17
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 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);
            }
        }
Пример #20
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);
            }
        }
Пример #21
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);
            }
        }
Пример #22
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);
            }
        }
        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);
            }
        }
Пример #24
0
        public void CreateUserAuthenticationMapping()
        {
            try
            {
                var dataSet = aHelper.GetAllUsers().Where(w => w.CPSiteId.Value == MigrationVariables.CurrentSiteId).ToList();
                RecordCount = dataSet.Count;

                foreach (var adUser in dataSet)
                {
                    aspnet_Membership  member;
                    aspnet_Users       aspUser;
                    UserAuthentication uAuth = null;
                    Guid appId           = nHelper.GetApplicationId("Diabetes Partner");
                    bool isAdmin         = (string.Equals(adUser.CliniProID, "admin", StringComparison.CurrentCultureIgnoreCase)) ? true : false;
                    bool isAdminSiteUser = false;

                    if (isAdmin)
                    {
                        switch (aHelper.GetCorporationName(adUser.CPSiteId))
                        {
                        case "Insulet":
                            appId = nHelper.GetApplicationId("OmniPod Partner");
                            break;

                        case "CliniProWeb":
                            appId = nHelper.GetApplicationId("CliniPro-Web");
                            break;

                        case "NuMedics":
                        default:
                            appId           = nHelper.GetApplicationId("Administration");
                            isAdminSiteUser = true;
                            break;
                        }
                    }

                    member  = aHelper.GetMembershipInfo(adUser.UserId);
                    aspUser = aHelper.GetAspUserInfo(adUser.UserId);

                    if (mHelper.HasUserMigrated(aspUser.UserName, member.UserId))
                    {
                        MappingStatistics.LogFailedMapping("None", "None", "Users", typeof(User), String.Empty, "User previously migrated.");
                        FailedCount++;
                    }
                    else
                    {
                        var userId = nHelper.ValidGuid(adUser.UserId);

                        uAuth = new UserAuthentication
                        {
                            ApplicationId              = appId,
                            UserId                     = userId,
                            Username                   = aspUser.UserName,
                            Password                   = member.Password,
                            PasswordQuestion           = member.PasswordQuestion,
                            PasswordAnswer             = member.PasswordAnswer,
                            PasswordAnswerFailureCount = member.FailedPasswordAnswerAttemptCount,
                            PasswordFailureCount       = member.FailedPasswordAttemptCount,
                            LastActivityDate           = aspUser.LastActivityDate,
                            LastLockOutDate            = member.LastLockoutDate,
                            IsApproved                 = member.IsApproved,
                            IsLockedOut                = member.IsLockedOut,
                            IsTempPassword             = member.IsTemp,
                            IsloggedIn                 = false,
                            LastUpdatedByUser          = userId
                        };

                        var user = new User
                        {
                            UserId            = userId,
                            AssignedUserTypes = new List <AssignedUserType> {
                                new AssignedUserType {
                                    UserId = userId, UserType = (isAdmin) ? (int)UserType.Clinician : (int)UserType.Patient
                                }
                            },
                            //UserType = (isAdmin) ? (int)UserType.Clinician : (int)UserType.Patient,
                            CreationDate = member.CreateDate
                        };

                        if (isAdminSiteUser)
                        {
                            user.AssignedUserTypes.Add(new AssignedUserType {
                                UserId = userId, UserType = (int)UserType.Admin
                            });
                        }

                        user.UserAuthentications.Add(uAuth);

                        // add user info to in-memery collection for use throughout application
                        MemoryMappings.AddPatientInfo(adUser.CPSiteId.Value, adUser.CliniProID, user.UserId);

                        if (CanAddToContext(user.UserId))
                        {
                            CompletedMappings.Add(user);
                        }
                        else
                        {
                            MappingStatistics.LogFailedMapping("None", "None", "Users", typeof(User), JsonConvert.SerializeObject(user), "User already exist in database.");
                            FailedCount++;
                        }
                    }
                }

                MappingStatistics.LogMappingStat("None", 0, "Users", CompletedMappings.Count, FailedCount);
            }
            catch (Exception e)
            {
                throw new Exception("Error creating User 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);
        }
        private void NoReadingTypeMatch(DataRow row)
        {
            var primeKey = $"{row["DOWNLOADKEYID"].ToString()}-{row["SEQ"].ToString()}";

            MappingStatistics.LogFailedMapping("METERREADING", primeKey, "", typeof(DataRow), JsonConvert.SerializeObject(row), "Failed to parse METERREADING row.");
        }
        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));
        }