/// <summary>
        /// Extracts the and save3.
        /// </summary>
        /// <param name="line">The line.</param>
        /// <param name="errors">The errors.</param>
        private void ExtractAndSave3(string[] line, IList <ImportError> errors)
        {
            //var line = csvRdr.ReadFields();
            try
            {
                SaveLine2(line, errors);

                if (errors.Count == 0)
                {
                    CountInserted++;
                }
            }
            catch (Exception exc)
            {
                var name         = GetName(line);
                var errorMessage =
                    string.Format(
                        "An error occurred while trying to save hospital categories for \"{1}\":{0}{2}."
                        , System.Environment.NewLine, name, (exc.InnerException ?? exc).Message);

                errors.Add(ImportError.Create("Hospital", name, errorMessage));
                //try
                //{
                //    using (var sw = new StreamWriter(ErrorFile, true))
                //    {
                //        WriteError(sw, ex);
                //        sw.WriteLine("Data: {0}", line);
                //        sw.WriteLine();
                //    }
                //}
                //finally
                //{
                //    this.NumberOfErrors++;
                //}
            }
            finally
            {
                if (errors.Count > 0)
                {
                    //Task.Factory.StartNew(() =>
                    //    {
                    using (var sw = new StreamWriter(ErrorFile, true))
                    {
                        foreach (var error in errors)
                        {
                            WriteError2(sw, error.ErrorMessage);
                            sw.WriteLine("Data: {0}", line);
                            sw.WriteLine();

                            this.NumberOfErrors++;
                        }
                    }
                    // });
                }
                LinesRead++;
            }
        }
        /// <summary>
        /// Validates the value count.
        /// </summary>
        /// <param name="vals">The vals.</param>
        /// <param name="errors">The errors.</param>
        public virtual void ValidateValueCount(string[] vals, IList <ImportError> errors)
        {
            if (vals.Length != ExpectedCountOfValuesPerLine)
            {
                var errorMessage = string.Format("{0} import requires {1} values per line. {2} values read.",
                                                 ExportAttribute.ContractName, ExpectedCountOfValuesPerLine,
                                                 vals.Length);
                errors.Add(ImportError.Create("", GetName(vals), errorMessage));

                //throw new Exception(string.Format("{0} import requires {1} values per line. {2} values read.",
                //        ExportAttribute.ContractName, ExpectedCountOfValuesPerLine,
                //        vals.Length));
            }
        }
        /// <summary>
        /// Extracts the and save2.
        /// </summary>
        /// <param name="csvRdr">The CSV RDR.</param>
        /// <param name="errors">The errors.</param>
        private void ExtractAndSave2(Microsoft.VisualBasic.FileIO.TextFieldParser csvRdr, IList <ImportError> errors)
        {
            string[] line = null;
            try
            {
                line = csvRdr.ReadFields();

                SaveLine2(line, errors);

                if (!errors.Any())
                {
                    CountInserted++;
                }
            }
            catch (Exception exc)
            {
                var name         = GetName(line);
                var errorMessage =
                    string.Format(
                        "An error occurred while trying to save hospital categories for \"{1}\":{0}{2}."
                        , System.Environment.NewLine, name, (exc.InnerException ?? exc).Message);

                errors.Add(ImportError.Create("Hospital", name, errorMessage));
            }
            finally
            {
                if (errors.Any())
                {
                    //Task.Factory.StartNew(() =>
                    //    {
                    using (var sw = new StreamWriter(ErrorFile, true))
                    {
                        foreach (var error in errors)
                        {
                            WriteError2(sw, error.ErrorMessage);
                            sw.WriteLineAsync(line != null
                                ? string.Format("Data: {0}", string.Join(",", line.ToArray()))
                                : error.ErrorMessage);

                            sw.WriteLine();

                            NumberOfErrors++;
                        }
                    }
                }
                LinesRead++;
            }
        }
        /// <summary>
        /// Processes the region population strats.
        /// </summary>
        /// <param name="regionPopulationStrats">The region population strats.</param>
        /// <param name="errors">The errors.</param>
        private void ProcessRegionPopulationStrats(RegionPopulationStrats regionPopulationStrats, IList <ImportError> errors)
        {
            try
            {
                if (errors.Any())
                {
                    return;
                }

                HospitalRegistryService.Save(regionPopulationStrats);
            }
            catch (Exception exc)
            {
                errors.Add(ImportError.Create(typeof(RegionPopulationStrats).Name, regionPopulationStrats.RegionID.ToString(), (exc.InnerException ?? exc).Message));
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Processes the region.
        /// </summary>
        /// <param name="region">The region.</param>
        /// <param name="errors">The errors.</param>
        private void ProcessRegion(CustomRegion region, IList <ImportError> errors)
        {
            var criteria      = PredicateBuilder.False <CustomRegion>().Or(r => r.ImportRegionId == region.ImportRegionId);
            var stateCriteria = PredicateBuilder.False <CustomRegion>();

            CurrentStatesBeingManaged.ToList().ForEach(abbr => stateCriteria = stateCriteria.Or(r => region.State.ToUpper() == abbr.ToUpper()));
            criteria = criteria.And(stateCriteria);

            var reg = GetExistingRegion(criteria);

            if (reg != null)
            {
                // if the found region is custom type, overwrite it in the database with the attributes being imported
                region.Code        = region.Code;
                reg.Name           = region.Name;
                reg.State          = region.State;
                reg.ImportRegionId = region.ImportRegionId;
            }
            else
            {
                reg = region;
            }

            if (CurrentStatesBeingManaged.All(s => s.ToLower() != reg.State.ToLower()))
            {
                var errorMessage =
                    string.Format(
                        "The region \"{0}\" can't be added because it is not in the correct geo context state. CMS NUMBER: {0}",
                        reg.Name);

                errors.Add(ImportError.Create("CustomRegion", reg.Name, errorMessage));
                return;
            }

            if (errors.Any())
            {
                return;
            }

            HospitalRegistryService.Save(reg);

            Events.GetEvent <EntityImportedEvent <CustomRegion> >().Publish(reg);
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public override void Execute()
        {
            var configService = ServiceLocator.Current.GetInstance <IConfigurationService>();
            var obj           = new object[] { };
            var version       = DateTime.Now.Ticks;

            NumberOfErrors = 0;
            AssertErrorFile();

            var startTime = DateTime.Now;
            var states    = configService.HospitalRegion.DefaultStates.OfType <string>().ToList();

            var dlg = new Microsoft.Win32.OpenFileDialog
            {
                DefaultExt = FileExtension,
                Filter     = "csv files (*.csv)|*.csv|All files (*.*)|*.*"
            };

            if (!dlg.ShowDialog().GetValueOrDefault())
            {
                return;
            }

            if (PromptUserForContinue() == MessageBoxResult.No)
            {
                return;
            }

            if (!ValidateImportFileName(dlg.FileName))
            {
                var message = string.Format("The file \"{0}\" could not be import due to the name containing special characters and/or dashes (-). Please remove these special characters and dashes to spaces and/or underscores and try again.", Path.GetFileName(dlg.FileName));
                MessageBox.Show(message, "MONAHRQ Import File Open Error", MessageBoxButton.OK);
                return;
            }

            try
            {
                OnImporting(this, EventArgs.Empty);

                BeginImport();

                var uploadFilePath = dlg.FileName;
                //var fileName = Regex.Replace(Path.GetFileName(uploadFilePath), "[^a-zA-Z0-9_]+", "_").Replace("-", "_");

                var tb = new DataTable("Temp");
                lock (obj)
                {
                    using (var connection = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source= " +
                                                                Path.GetDirectoryName(uploadFilePath) + "; Extended Properties= \"Text;HDR=YES;FMT=Delimited\""))
                    {
                        connection.Open();


                        using (var cmd = new OleDbCommand("SELECT * FROM " + Path.GetFileName(uploadFilePath), connection))
                        {
                            using (var reader = cmd.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    tb.Load(reader);
                                }
                            }
                        }
                    }
                }

                var actualStates = tb.Rows.OfType <DataRow>()
                                   .Where(dr => dr["State"] != DBNull.Value)
                                   .Select(dr => dr["State"].ToString())
                                   .Distinct()
                                   .ToList();

                int rowCount = 0;
                foreach (DataRow row in tb.Rows)
                {
                    var  state = row["State"].ToString();
                    long npi   = 0;

                    if (row["NPI"] != DBNull.Value)
                    {
                        npi = long.Parse(row["NPI"].ToString());
                    }

                    if (!states.Contains(state))
                    {
                        var message = new StringBuilder();
                        message.AppendLine(
                            string.Format(
                                "The Physician record being imported is not with in the selected state context of \"{0}\"",
                                string.Join(",", states)));
                        message.AppendLine(string.Format("Data: {0}", string.Join(",", row.ItemArray)));
                        ImportErrors.Add(ImportError.Create("Physician", "Physician", message.ToString()));
                        continue;
                    }

                    if (CheckIfAlreadyExists(npi, state))
                    {
                        var message = new StringBuilder();
                        message.AppendLine(
                            string.Format(
                                "The Physician record with NPI \"{0}\" already exists and can't be imported. Please choose an unique NPI number.",
                                npi));
                        message.AppendLine(string.Format("Data: {0}", string.Join(",", row.ItemArray)));
                        ImportErrors.Add(ImportError.Create("Physician", "Physician", message.ToString()));
                        continue;
                    }

                    var tRow = _physiciansTable.NewRow();

                    tRow["Npi"]                            = npi;
                    tRow["PacId"]                          = row["PAC ID"];
                    tRow["ProfEnrollId"]                   = row["Professional Enrollment ID"];
                    tRow["LastName"]                       = row["Last Name"];
                    tRow["FirstName"]                      = row["First Name"];
                    tRow["MiddleName"]                     = row["Middle Name"];
                    tRow["Suffix"]                         = row["Suffix"];
                    tRow["Gender"]                         = row["Gender"];
                    tRow["Credential"]                     = row["Credential"];
                    tRow["MedicalSchoolName"]              = row["Medical school name"];
                    tRow["GraduationYear"]                 = row["Graduation year"];
                    tRow["PrimarySpecialty"]               = row["Primary specialty"];
                    tRow["SecondarySpecialty1"]            = row["Secondary specialty 1"];
                    tRow["SecondarySpecialty2"]            = row["Secondary specialty 2"];
                    tRow["SecondarySpecialty3"]            = row["Secondary specialty 3"];
                    tRow["SecondarySpecialty4"]            = row["Secondary specialty 4"];
                    tRow["AllSecondarySpecialties"]        = row["All secondary specialties"];
                    tRow["OrgLegalName"]                   = row["Organization legal name"];
                    tRow["DBAName"]                        = DBNull.Value; // row["Organization DBA name"];
                    tRow["GroupPracticePacId"]             = row["Group Practice PAC ID"];
                    tRow["NumberofGroupPracticeMembers"]   = row["Number of Group Practice members"];
                    tRow["Line1"]                          = row["Line 1 Street Address"];
                    tRow["Line2"]                          = row["Line 2 Street Address"];
                    tRow["MarkerofAdressLine2Suppression"] = row["Marker of address line 2 suppression"] ==
                                                             DBNull.Value ||
                                                             row["Marker of address line 2 suppression"]
                                                             .ToString() == "N"
                                                                         ? 0
                                                                         : 1;
                    tRow["City"]    = row["City"];
                    tRow["State"]   = row["State"];
                    tRow["ZipCode"] = row["Zip Code"];

                    if (row["Hospital affiliation CCN 1"] != DBNull.Value)
                    {
                        tRow["HospitalAffiliationCCN1"] = row["Hospital affiliation CCN 1"].ToString().PadLeft(6, '0');
                    }

                    tRow["HospitalAffiliationLBN1"] = row["Hospital affiliation LBN 1"];
                    if (row["Hospital affiliation CCN 2"] != DBNull.Value)
                    {
                        tRow["HospitalAffiliationCCN2"] = row["Hospital affiliation CCN 2"].ToString().PadLeft(6, '0');
                    }

                    tRow["HospitalAffiliationLBN2"] = row["Hospital affiliation LBN 2"];
                    if (row["Hospital affiliation CCN 3"] != DBNull.Value)
                    {
                        tRow["HospitalAffiliationCCN3"] = row["Hospital affiliation CCN 3"].ToString().PadLeft(6, '0');
                    }

                    tRow["HospitalAffiliationLBN3"] = row["Hospital affiliation LBN 3"];
                    if (row["Hospital affiliation CCN 4"] != DBNull.Value)
                    {
                        tRow["HospitalAffiliationCCN4"] = row["Hospital affiliation CCN 4"].ToString().PadLeft(6, '0');
                    }

                    tRow["HospitalAffiliationLBN4"] = row["Hospital affiliation LBN 4"];
                    if (row["Hospital affiliation CCN 5"] != DBNull.Value)
                    {
                        tRow["HospitalAffiliationCCN5"] = row["Hospital affiliation CCN 5"].ToString().PadLeft(6, '0');
                    }

                    tRow["HospitalAffiliationLBN5"] = row["Hospital affiliation LBN 5"];

                    tRow["AcceptsMedicareAssignment"] = row["Professional accepts Medicare Assignment"];
                    tRow["ParticipatesInERX"]         = DBNull.Value;
                    tRow["ParticipatesInPQRS"]        = row["Reported Quality Measures"] == DBNull.Value ||
                                                        row["Reported Quality Measures"].ToString() == "N"
                                                             ? 0
                                                             : 1;
                    tRow["ParticipatesInEHR"] = row["Used electronic health records"] == DBNull.Value ||
                                                row["Used electronic health records"].ToString() == "N"
                                                            ? 0
                                                            : 1;

                    //tRow["ParticipatesInERX"] = row["Participating in eRx"] == DBNull.Value ||
                    //                                    row["Participating in eRx"].ToString() == "N"
                    //                                        ? 0
                    //                                        : 1;
                    //tRow["ParticipatesInPQRS"] = row["Participating in PQRS"] == DBNull.Value ||
                    //                                     row["Participating in PQRS"].ToString() == "N"
                    //                                         ? 0
                    //                                         : 1;
                    //tRow["ParticipatesInEHR"] = row["Participating in EHR"] == DBNull.Value ||
                    //                                    row["Participating in EHR"].ToString() == "N"
                    //                                        ? 0
                    //                                        : 1;
                    tRow["IsEdited"] = 1;

                    _physiciansTable.Rows.Add(tRow);

                    rowCount++;

                    Events.GetEvent <PleaseStandByMessageUpdateEvent>()
                    .Publish("Importing line " + rowCount.ToString());
                }

                //if (_physiciansTable.Rows.Count == BATCH_SIZE)
                //{
                BulkInsert(_physiciansTable, _configurationService.ConnectionSettings.ConnectionString,
                           _physiciansTable.Rows.Count);
                CountInserted = _physiciansTable.Rows.Count;
                //}_

                foreach (var contextState in actualStates)
                {
                    var physicianScript = ReflectionHelper.ReadEmbeddedResourceFile(GetType().Assembly,
                                                                                    "Monahrq.Sdk.Resources.PhysiciansImport.ImportUpdatePhysicians.sql")
                                          .Replace("[@@State@@]", contextState);
                    var medPracticeScript = ReflectionHelper.ReadEmbeddedResourceFile(GetType().Assembly,
                                                                                      "Monahrq.Sdk.Resources.PhysiciansImport.ImportUpdateMedicalPractices.sql")
                                            .Replace("[@@State@@]", contextState);
                    var physicianMedPracticeScript = ReflectionHelper.ReadEmbeddedResourceFile(GetType().Assembly,
                                                                                               "Monahrq.Sdk.Resources.PhysiciansImport.ImportUpdatePhysiciansMedPractices.sql")
                                                     .Replace("[@@State@@]", contextState);

                    var completQuery = new StringBuilder();

                    completQuery.AppendLine(physicianScript);
                    completQuery.AppendLine(medPracticeScript);
                    completQuery.AppendLine(physicianMedPracticeScript);

                    var combinedQueries = completQuery.ToString();

                    using (var session = Provider.SessionFactory.OpenStatelessSession())
                    {
                        using (var trans = session.BeginTransaction())
                        {
                            session.CreateSQLQuery(combinedQueries)
                            .SetTimeout(10000)
                            .ExecuteUpdate();

                            trans.Commit();
                        }
                    }

                    //CountInserted = GetTotalItemsSaved(typeof(Physician), "Npi",
                    //                                              string.Format("Where [States]='{0}';", contextState));
                    //var totalMedicalPracticesSaved = GetTotalItemsSaved(typeof (MedicalPractice), "GroupPracticePacId",
                    //                                                    string.Format("Where [State]='{0}';",
                    //                                                                  contextState));
                }

                Events.GetEvent <PleaseStandByMessageUpdateEvent>().Publish("Finalizing import...");

                // what is the purpose of this delay???
                const int MAX_DELAY_SECONDS = 3;

                var elapsed   = DateTime.Now - startTime;
                var seconds   = elapsed.TotalSeconds;
                var remaining = MAX_DELAY_SECONDS - seconds;
                if (remaining > 0)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(remaining));
                }
            }
            catch (IOException exc)
            {
                Logger.Write(exc, "Error importing data from file {0}", dlg.FileName);

                var message = string.Format("Please close file\"{0}\" before trying to import.",
                                            dlg.FileName.SubStrAfterLast(@"\"));
                MessageBox.Show(message, "MONAHRQ Import File Open Error", MessageBoxButton.OK);
            }
            catch (Exception exc)
            {
                Logger.Write(exc, "Error importing data from file {0}", dlg.FileName);
                ImportErrors.Add(ImportError.Create("Physician", "Physician", exc.GetBaseException().Message));
            }
            finally
            {
                EndImport();

                if (ImportErrors.Any())
                {
                    //Task.Factory.StartNew(() =>
                    //{
                    using (var sw = new StreamWriter(ErrorFile, true))
                    {
                        foreach (var error in ImportErrors)
                        {
                            WriteError2(sw, error.ErrorMessage);
                            sw.WriteLine();

                            NumberOfErrors++;
                        }
                    }
                    //});
                }

                OnImported(this, EventArgs.Empty);
                Events.GetEvent <PleaseStandByMessageUpdateEvent>().Publish("Import Complete");
                Events.GetEvent <SimpleImportCompletedEvent>().Publish(this);
            }
        }