private void SerializeandSave(string fileName, AccountEventZipSetting setting)
        {
            if (setting == null)
            {
                return;
            }

            var serializer = new XmlSerializer(setting.GetType());

            if (Path.GetDirectoryName(fileName) == null || !DirectoryOperationsHelper.IsDirectoryExist(Path.GetDirectoryName(fileName)))
            {
                DirectoryOperationsHelper.CreateDirectory(Path.GetDirectoryName(fileName));
            }

            if (DirectoryOperationsHelper.IsFileExist(fileName))
            {
                DirectoryOperationsHelper.Delete(fileName);
            }

            var stream = new StreamWriter(fileName);

            serializer.Serialize(stream, setting);

            stream.Close();
            stream.Dispose();
        }
Exemplo n.º 2
0
        private void DeleteIffileExist(string destinationPath, int year)
        {
            var files = DirectoryOperationsHelper.GetFiles(destinationPath, "*.csv");

            foreach (var file in files)
            {
                if (!string.IsNullOrEmpty(file) && file.Contains("HomeVisitRequested_") && file.Contains("_" + year))
                {
                    if (DirectoryOperationsHelper.IsFileExist(file))
                    {
                        DirectoryOperationsHelper.Delete(file);
                    }
                }
            }
        }
Exemplo n.º 3
0
        public string DownloadZipFile(MediaLocation mediaLocation, string csvfileName, long userId, ILogger logger)
        {
            var csvFilePath = mediaLocation.PhysicalPath + csvfileName;
            var fileName    = string.Empty;

            try
            {
                var isPinRequired = false;
                var user          = _userRepository.GetUser(userId);
                var orgRoles      = _organizationRoleUserRepository.GetOrganizationRoleUserCollectionforaUser(userId);
                var defaultRole   = orgRoles.FirstOrDefault(oru => oru.RoleId == (long)user.DefaultRole);
                if (defaultRole != null)
                {
                    Role role = _roleRepository.GetByRoleId(defaultRole.RoleId);
                    isPinRequired = role.IsPinRequired;
                }
                var password = "";
                if (isPinRequired)
                {
                    var userSetting = _loginSettingRepository.Get(userId);
                    if (userSetting != null)
                    {
                        password = userSetting.DownloadFilePin;
                    }
                }

                string zipFilePath = _zipHelper.CreateZipOfSingleFile(csvFilePath, password);

                fileName = Path.GetFileName(zipFilePath);
                if (fileName == null || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
                {
                    throw new InvalidFileNameException();
                }
            }
            finally
            {
                try
                {
                    DirectoryOperationsHelper.Delete(csvFilePath);
                }
                catch (Exception ex)
                {
                    logger.Error("exception Message : " + ex.Message + " Stack Trace :" + ex.StackTrace);
                }
            }

            return(fileName);
        }
        private void DownloadAttestationForm(string sourceFile, string destinationFolder, string destinationFileName = "")
        {
            if (DirectoryOperationsHelper.IsDirectoryExist(destinationFolder))
            {
                var fileName = !string.IsNullOrEmpty(destinationFileName) ? destinationFileName : Path.GetFileNameWithoutExtension(sourceFile) + ".pdf";
                destinationFileName = Path.Combine(destinationFolder, fileName);

                _logger.Info("source: " + sourceFile);
                _logger.Info("destination: " + destinationFileName);

                if (DirectoryOperationsHelper.IsFileExist(destinationFileName))
                {
                    DirectoryOperationsHelper.Delete(destinationFileName);
                }

                DirectoryOperationsHelper.Copy(sourceFile, destinationFileName);
            }
        }
        private string GetCsvFileName(CorporateAccount account, string fileName)
        {
            var folderLocation = string.Format(_wellmedMemberStatusDestinationPath, account.FolderName, DateTime.Today.Year);

            if (!DirectoryOperationsHelper.IsDirectoryExist(folderLocation))
            {
                DirectoryOperationsHelper.CreateDirectory(folderLocation);
            }

            var destinationFileName = Path.Combine(folderLocation, fileName);

            if (DirectoryOperationsHelper.IsFileExist(destinationFileName))
            {
                DirectoryOperationsHelper.Delete(destinationFileName);
            }

            return(destinationFileName);
        }
        public string CheckIsFileContainsRecord(MediaLocation mediaLocation, string filePath)
        {
            try
            {
                var customerTable = _csvReader.ReadWithTextQualifier(mediaLocation.PhysicalPath + filePath);

                if (customerTable.Rows.Count > 0)
                {
                    return(mediaLocation.Url + filePath);
                }

                DirectoryOperationsHelper.Delete(filePath);
            }
            catch (Exception)
            {
            }

            return(string.Empty);
        }
Exemplo n.º 7
0
        private string[] GetFiles(string eventID, string pdftype, out string allresultfilepath, out string allresultpdfurl)
        {
            string extractingpdfpath = "";
            string extractingpdfurl  = "";

            if (pdftype.Equals(EPDFType.ClinicalForm.ToString()))
            {
                extractingpdfpath = CustomerResultsReportPDFSavePath + eventID.ToString() + "\\" + ConfigurationManager.AppSettings["ClinicalFormFolderName"];
                extractingpdfurl  = CustomerResultsReportPDFPath + eventID.ToString() + "/" + ConfigurationManager.AppSettings["ClinicalFormFolderName"];
            }
            else
            {
                extractingpdfpath = CustomerResultsReportPDFSavePath + eventID.ToString() + "\\" + ConfigurationManager.AppSettings["ResultPDFFolderName"];
                extractingpdfurl  = CustomerResultsReportPDFPath + eventID.ToString() + "/" + ConfigurationManager.AppSettings["ResultPDFFolderName"];
            }


            if (File.Exists(extractingpdfpath + "\\AllResults_" + eventID + ".pdf"))
            {
                DirectoryOperationsHelper.Delete(extractingpdfpath + "\\AllResults_" + eventID + ".pdf");
            }

            allresultfilepath = extractingpdfpath + "\\AllResults_" + eventID + ".pdf";
            allresultpdfurl   = extractingpdfurl + "/AllResults_" + eventID + ".pdf";

            ArrayList     list    = new ArrayList();
            DirectoryInfo dirInfo = new DirectoryInfo(extractingpdfpath);

            if (dirInfo.Exists)
            {
                FileInfo[] fileInfos = dirInfo.GetFiles("*.pdf");
                foreach (FileInfo info in fileInfos)
                {
                    if (info.Name.IndexOf("protected") == -1)
                    {
                        list.Add(info.FullName);
                    }
                }
            }
            return((string[])list.ToArray(typeof(string)));
        }
Exemplo n.º 8
0
        public void HideEcgFinding(string fromImagePath, string toSaveImagePath, ILogger logger, IEnumerable <RectangleDimesion> rectangles)
        {
            if (fromImagePath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                throw new InvalidDirectoryPathException();
            }
            if (toSaveImagePath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                throw new InvalidDirectoryPathException();
            }
            var      image    = new Bitmap(fromImagePath);
            Graphics graphics = Graphics.FromImage(image);

            try
            {
                if (rectangles != null && rectangles.Count() > 0)
                {
                    foreach (var rectangleDimesion in rectangles)
                    {
                        graphics.FillRectangle(Brushes.White, rectangleDimesion.PositionX, rectangleDimesion.PositionY, rectangleDimesion.Width, rectangleDimesion.Heigth);
                    }
                }

                image.Save(toSaveImagePath);
            }
            catch (Exception ex)
            {
                logger.Error("System Failure! Unable to hide ECG findings. Message: " + ex.Message + " \n\t " +
                             ex.StackTrace);
            }
            finally
            {
                image.Dispose();
                graphics.Dispose();
                DirectoryOperationsHelper.Delete(fromImagePath);
            }
        }
        private void AttachAttestationForm(string sourcePath, string searchPattern, string destinationFolder, string destinationFileName = "")
        {
            if (DirectoryOperationsHelper.IsDirectoryExist(sourcePath))
            {
                var files = DirectoryOperationsHelper.GetFiles(sourcePath, "*" + searchPattern + ".pdf");
                if (files != null && files.Any())
                {
                    foreach (var file in files)
                    {
                        var destinationFile = Path.Combine(destinationFolder, !string.IsNullOrEmpty(destinationFileName) ? destinationFileName + ".pdf" : Path.GetFileNameWithoutExtension(file) + ".pdf");
                        if (DirectoryOperationsHelper.IsFileExist(destinationFile))
                        {
                            DirectoryOperationsHelper.Delete(destinationFile);
                        }

                        DirectoryOperationsHelper.Copy(file, destinationFile);
                    }
                }
                else
                {
                    _logger.Info(string.Format("No file Found in folder : {0} for search pattern : {1}", sourcePath, searchPattern));
                }
            }
        }
Exemplo n.º 10
0
        public void GenerateHafAssessment(long eventId)
        {
            try
            {
                var eventLogger = _logManager.GetLogger("HealthAssessmentFormGenerator_" + eventId);
                eventLogger.Info("Generating HAF for Event Id: " + eventId);
                _pdfGenerator.PaperSize = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.PaperSize);

                try
                {
                    var eventCustomers = _eventCustomerRepository.GetbyEventId(eventId);

                    if (eventCustomers != null && eventCustomers.Any())
                    {
                        eventCustomers = eventCustomers.Where(ec => ec.AppointmentId.HasValue).ToArray();

                        if (eventCustomers != null && eventCustomers.Any())
                        {
                            eventLogger.Info("found EventCustomers Count: " + eventCustomers.Count());

                            var mediaLocation = _mediaRepository.GetMedicalHistoryMediaLocation(eventId);

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(mediaLocation.PhysicalPath);

                            DirectoryOperationsHelper.DeleteFiles(mediaLocation.PhysicalPath);
                            var eventData = _eventRepository.GetById(eventId);
                            var account   = _corporateAccountRepository.GetbyEventId(eventId);

                            var corporateSurveyPdf = "";
                            if (account != null && account.CaptureSurvey)
                            {
                                if (account.SurveyPdfFileId > 0)
                                {
                                    var surveyPdf = _fileRepository.GetById(account.SurveyPdfFileId);
                                    if (surveyPdf != null)
                                    {
                                        corporateSurveyPdf = _mediaRepository.GetCorporateSurveyPdfFolderLocation().PhysicalPath + surveyPdf.Path;
                                    }
                                }
                            }

                            var corporateCheckListPdf = "";
                            if (account != null && account.PrintCheckList && account.CheckListFileId > 0 && eventData.EventDate >= _settings.ChecklistChangeDate)
                            {
                                var checkListFilePdf = _fileRepository.GetById(account.CheckListFileId);
                                if (checkListFilePdf != null)
                                {
                                    corporateCheckListPdf = _mediaRepository.GetCorporateCheckListPdfFolderLocation().PhysicalPath + checkListFilePdf.Path;
                                }
                            }

                            var filesFocAttestation    = new[] { "" };
                            var mediaLocFocAttestation = _mediaRepository.GetUnlockEventsParseLocation(eventId);

                            if (account != null && account.Id == _settings.HcpNvAccountId)
                            {
                                if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath))
                                {
                                    filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.*");
                                    filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray();
                                }
                            }
                            else
                            {
                                if (DirectoryOperationsHelper.IsDirectoryExist(mediaLocFocAttestation.PhysicalPath))
                                {
                                    filesFocAttestation = Directory.GetFiles(mediaLocFocAttestation.PhysicalPath, "*.pdf");
                                    filesFocAttestation = filesFocAttestation.Where(fsd => !string.IsNullOrEmpty(fsd)).ToArray();
                                }
                            }

                            var tempMediaLocation = _mediaRepository.GetTempMediaFileLocation();
                            var customers         = _customerRepository.GetCustomers(eventCustomers.Select(ec => ec.CustomerId).ToArray());

                            int index = 0;
                            foreach (var eventCustomer in eventCustomers)
                            {
                                eventLogger.Info(string.Format("Generating HAF for Event Id: {0} and Customer Id : {1} ", eventId, eventCustomer.CustomerId));
                                string url                = _settings.HealthAssessmentFormUrl + string.Format("?eventId={0}&customerId={1}&LoadLayout=false&showKynEditModel=true&bulkPrint=true&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid());
                                var    customer           = customers.First(c => c.CustomerId == eventCustomer.CustomerId);
                                var    focAttestationFile = string.Empty;

                                if (account != null)
                                {
                                    var questFile = Path.Combine(_mediaRepository.GetQuestUploadMediaFileLocation().PhysicalPath, account.Tag + "_Quest.pdf");

                                    if (account.Id == _settings.WellmedAccountId || account.Id == _settings.WellmedTxAccountId)
                                    {
                                        var memberId = string.IsNullOrEmpty(customer.InsuranceId) ? "" : customer.InsuranceId.ToLower().Trim();
                                        focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == memberId);
                                        eventLogger.Info(string.Format("focAttestationFile : {0}", focAttestationFile));

                                        var _files = new List <string>();

                                        if (!string.IsNullOrEmpty(focAttestationFile) && DirectoryOperationsHelper.IsFileExist(focAttestationFile))
                                        {
                                            eventLogger.Info(string.Format("focAttestationFile : First if {0}", focAttestationFile));
                                            _files.Add(focAttestationFile);
                                        }

                                        if (DirectoryOperationsHelper.IsFileExist(questFile))
                                        {
                                            eventLogger.Info(string.Format("focAttestationFile : 2nd if {0}", questFile));
                                            _files.Add(questFile);
                                        }

                                        if (!_files.IsNullOrEmpty())
                                        {
                                            if (_files.Count() > 1)
                                            {
                                                eventLogger.Info(string.Format("focAttestationFile : File Count {0}", _files.Count()));
                                                focAttestationFile = GetFocAttestationFileMerge(_files, focAttestationFile, eventLogger);
                                            }
                                            else
                                            {
                                                eventLogger.Info(string.Format("focAttestationFile : File[0] {0}", _files[0]));
                                                focAttestationFile = _files[0];
                                                eventLogger.Info(string.Format("focAttestationFile : Last {0}", focAttestationFile));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        focAttestationFile = GetFocAttestationFileForMht(filesFocAttestation, customer.CustomerId.ToString(), eventLogger);
                                    }
                                    //else if (account.Id == _settings.MolinaAccountId)
                                    //{
                                    //    var hicn = string.IsNullOrEmpty(customer.Hicn) ? "" : customer.Hicn.ToLower().Trim();
                                    //    focAttestationFile = filesFocAttestation.FirstOrDefault(fsd => !string.IsNullOrEmpty(fsd) && Path.GetFileNameWithoutExtension(fsd).ToLower().Trim() == hicn);
                                    //}
                                    //else if (account.Id == _settings.HcpNvAccountId)
                                    //{

                                    //}
                                    //else if (_settings.MonarchAccountIds.Contains(account.Id))
                                    //{
                                    //    var gmpi = string.IsNullOrEmpty(customer.AdditionalField4) ? "" : customer.AdditionalField4.ToLower().Trim();

                                    //    if (!string.IsNullOrEmpty(gmpi))
                                    //    {
                                    //        focAttestationFile = GetFocAttestationFile(filesFocAttestation, "_" + gmpi.ToLower(), focAttestationFile, eventLogger);
                                    //    }
                                    //}
                                    //else if (account.Id == _settings.AppleCareAccountId)
                                    //{
                                    //    focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger);
                                    //}
                                    //else if (account.Id == _settings.NammAccountId)
                                    //{
                                    //    focAttestationFile = GetFocAttestationFile(filesFocAttestation, customer.CustomerId.ToString(), focAttestationFile, eventLogger);
                                    //}
                                }

                                var focAttestationFilePath = string.Empty;
                                eventLogger.Info("focAttestationFile: " + focAttestationFile);

                                if (!string.IsNullOrEmpty(focAttestationFile))
                                {
                                    focAttestationFilePath = focAttestationFile;
                                }

                                var annualComprehensiveExamPdf  = string.Empty;
                                var memberInformationProfilePdf = string.Empty;

                                if (!string.IsNullOrEmpty(customer.Hicn))
                                {
                                    var fileNamePattern = customer.Hicn + (customer.Name != null ? "_" + customer.Name.LastName + "_" + customer.Name.FirstName : "");
                                    if (account != null && account.PrintAceForm)
                                    {
                                        try
                                        {
                                            var mediaLocationForAce = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "ACE");
                                            var aceFiles            = DirectoryOperationsHelper.GetFiles(mediaLocationForAce.PhysicalPath, fileNamePattern + "*_ACE.pdf");
                                            if (aceFiles.Any())
                                            {
                                                annualComprehensiveExamPdf = _pdfGenerator.ExtractPdfPagesFromEnd(aceFiles.First(), tempMediaLocation.PhysicalPath + "Ripped_" + customer.Hicn + "_ACE.pdf", NumberOfPagesToExtractFromAcePdf);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            eventLogger.Error(string.Format("Unable to attach ACE form to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message));
                                        }
                                    }

                                    if (account != null && account.PrintMipForm)
                                    {
                                        try
                                        {
                                            var mediaLocationForMip = _mediaRepository.GetAceMipLocation(account.FolderName, fileNamePattern, "MIP");
                                            var mipFiles            = DirectoryOperationsHelper.GetFiles(mediaLocationForMip.PhysicalPath, fileNamePattern + "*_MIP.pdf");
                                            if (mipFiles.Any())
                                            {
                                                memberInformationProfilePdf = mipFiles.First();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            eventLogger.Error(string.Format("Unable to attach MIP to the bulk HAF for CustomerID : {0}\nMessage : {1}", customer.CustomerId, ex.Message));
                                        }
                                    }
                                }
                                var consentHeaderWithChecklistpdf = string.Empty;

                                if (!string.IsNullOrWhiteSpace(corporateCheckListPdf) && DirectoryOperationsHelper.IsFileExist(corporateCheckListPdf))
                                {
                                    var    tempPath         = _mediaRepository.GetTempMediaFileLocation();
                                    var    consentHeader    = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf");
                                    string consentHeaderUrl = _settings.ConsentHeaderFormUrl + string.Format("?eventId={0}&customerId={1}&removeChache={2}", eventCustomer.EventId, eventCustomer.CustomerId, Guid.NewGuid());
                                    _pdfGenerator.GeneratePdf(consentHeaderUrl, consentHeader);

                                    consentHeaderWithChecklistpdf = Path.Combine(tempPath.PhysicalPath, Guid.NewGuid() + ".pdf");
                                    var consentHeaderWithChecklistpdfArray = new string[] { consentHeader, corporateCheckListPdf };
                                    _pdfGenerator.Merge(consentHeaderWithChecklistpdf, consentHeaderWithChecklistpdfArray);
                                }


                                _pdfGenerator.GeneratePdfForHaf(url, mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf", corporateSurveyPdf, "", focAttestationFilePath, consentHeaderWithChecklistpdf,
                                                                annualComprehensiveExamPdf, memberInformationProfilePdf);
                            }

                            eventLogger.Info("Merging HAF for Event Id: " + eventId);
                            _pdfGenerator.GetPdffilesfromLocationandMergeintoOne(mediaLocation.PhysicalPath, mediaLocation.PhysicalPath + "Event_" + eventId + ".pdf");
                            _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);

                            index = 0;

                            foreach (var eventCustomer in eventCustomers)
                            {
                                DirectoryOperationsHelper.Delete(mediaLocation.PhysicalPath + (++index).ToString("000.") + eventCustomer.CustomerId + ".pdf");
                            }
                        }
                        else
                        {
                            eventLogger.Info("No customer found with appointment attached with this event. Merging HAF for Event Id: " + eventId);
                            _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);
                        }
                    }
                    else
                    {
                        eventLogger.Info("No customer found attached with this event. Merging HAF for Event Id: " + eventId);
                        _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, false, (long)GenerateHealthAssesmentFormStatus.Completed);
                    }
                }
                catch (Exception ex)
                {
                    _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending);
                    eventLogger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
                }
            }
            catch (Exception ex)
            {
                _eventRepository.SetGenrateHealthAssesmentFormStatus(eventId, true, (long)GenerateHealthAssesmentFormStatus.Pending);
                _logger.Error("\n" + ex.Message + "\n\t Stack Trace: " + ex.StackTrace);
            }
        }
Exemplo n.º 11
0
        private void GenerateCrosswalkInboundReport(CrosswalkInboundFilter filter)
        {
            var account = _corporateAccountRepository.GetById(filter.AccountId);

            filter.Tag = account.Tag;

            if (account.IsHealthPlan)
            {
                filter.StopSendingPdftoHealthPlanDate = _settings.StopSendingPdftoHealthPlanDate;
            }

            var model = _crosswalkInboundReportService.GetCrosswalkInboundReportList(filter, _logger);

            if (model != null)
            {
                var folder = string.Format(_settings.FloridaBlueInboundReportPath, account.FolderName, DateTime.Now.ToString("yyyy-MM-dd"));
                if (!Directory.Exists(folder))
                {
                    DirectoryOperationsHelper.CreateDirectory(folder);
                }
                var fileName    = _pipeDelimitedReportHelper.GetReportName(ReportType.CrosswalkInbound) + ".txt";
                var zipFileName = _pipeDelimitedReportHelper.GetReportName(ReportType.CrosswalkZip);

                if (model.Collection != null && model.Collection.Any())
                {
                    _logger.Info("generating File");
                    var tempMediaLocation = _mediaRepository.GetTempMediaFileLocation().PhysicalPath + zipFileName + "\\";
                    if (!Directory.Exists(tempMediaLocation))
                    {
                        DirectoryOperationsHelper.CreateDirectory(tempMediaLocation);
                    }

                    var resultPostedToPlanFileName = Path.Combine(_resultPostedToPlanPath, string.Format("ResultPostedto_{0}.xml", account.Tag));
                    var resultPosted = _resultPdfPostedSerializer.Deserialize(resultPostedToPlanFileName);
                    resultPosted = resultPosted == null || resultPosted.Customer.IsNullOrEmpty() ? new ResultPdfPostedXml {
                        Customer = new List <CustomerInfo>()
                    } : resultPosted;

                    foreach (var crosswalkViewModel in model.Collection)
                    {
                        var hafResultPdfLocation = _mediaRepository.GetPremiumVersionResultPdfLocation(crosswalkViewModel.EventId, crosswalkViewModel.CustomerId);
                        var hafResultPdfFileName = _mediaRepository.GetPdfFileNameForHealthPlanResultReport();
                        var pcpResultPdfFileName = _mediaRepository.GetPdfFileNameForPcpResultReport();

                        _logger.Info(" Event Id: " + crosswalkViewModel.EventId + " Customer Id: " + crosswalkViewModel.CustomerId);

                        if (DirectoryOperationsHelper.IsFileExist(tempMediaLocation + crosswalkViewModel.FileName))
                        {
                            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(tempMediaLocation + crosswalkViewModel.FileName);
                            var files = DirectoryOperationsHelper.GetFiles(tempMediaLocation, fileNameWithoutExtension + "*.pdf");
                            crosswalkViewModel.FileName = fileNameWithoutExtension + "_" + files.Count() + ".pdf";
                        }

                        if (File.Exists(hafResultPdfLocation.PhysicalPath + hafResultPdfFileName))
                        {
                            var destinationFileName = GetFileName(resultPosted.Customer, crosswalkViewModel.EventId, crosswalkViewModel.CustomerId, Path.GetFileNameWithoutExtension(crosswalkViewModel.FileName), (long)ResultFormatType.PDF);
                            crosswalkViewModel.FileName = destinationFileName + ".pdf";

                            _logger.Info("Copying File.. filePath from : " + hafResultPdfLocation.PhysicalPath + hafResultPdfFileName);
                            _logger.Info("Copying File.. filePath To : " + tempMediaLocation + crosswalkViewModel.FileName);

                            DirectoryOperationsHelper.Copy(hafResultPdfLocation.PhysicalPath + hafResultPdfFileName, tempMediaLocation + crosswalkViewModel.FileName);

                            resultPosted.Customer.Add(GetCustomerInfo(crosswalkViewModel));
                        }
                        else if (File.Exists(hafResultPdfLocation.PhysicalPath + pcpResultPdfFileName))
                        {
                            var destinationFileName = GetFileName(resultPosted.Customer, crosswalkViewModel.EventId, crosswalkViewModel.CustomerId, Path.GetFileNameWithoutExtension(crosswalkViewModel.FileName), (long)ResultFormatType.PDF);
                            crosswalkViewModel.FileName = destinationFileName + ".pdf";

                            _logger.Info("Copying File.. filePath from : " + hafResultPdfLocation.PhysicalPath + pcpResultPdfFileName);
                            _logger.Info("Copying File.. filePath To : " + tempMediaLocation + crosswalkViewModel.FileName);

                            DirectoryOperationsHelper.Copy(hafResultPdfLocation.PhysicalPath + pcpResultPdfFileName, tempMediaLocation + crosswalkViewModel.FileName);

                            resultPosted.Customer.Add(GetCustomerInfo(crosswalkViewModel));
                        }
                        else
                        {
                            _logger.Info("file not found");
                        }
                    }

                    _resultPdfPostedSerializer.SerializeandSave(resultPostedToPlanFileName, resultPosted);

                    _pipeDelimitedReportHelper.Write(model.Collection, folder, fileName);
                    DirectoryOperationsHelper.Copy(folder + "\\" + fileName, tempMediaLocation + fileName);

                    _logger.Info("generating Zip ");
                    _zipHelper.CreateZipFiles(tempMediaLocation, folder + "\\" + zipFileName + ".zip");

                    if (_sendReportToSftp)
                    {
                        try
                        {
                            _logger.Info("Sending zip to SFTP.");

                            var destinationPath = _destinationSftpPath + "\\" + account.FolderName + "\\Download\\Reports";
                            SendFilesToSftp(Path.Combine(folder, zipFileName + ".zip"), destinationPath, zipFileName + ".zip");

                            _logger.Info("Zip sent to SFTP.");
                        }
                        catch (Exception ex)
                        {
                            _logger.Info("Error sending zip to SFTP.");
                            _logger.Error("Message : " + ex.Message);
                            _logger.Error("Stack Trace : " + ex.StackTrace);
                        }
                    }

                    _logger.Info("Deleting temp folder: " + tempMediaLocation);
                    DirectoryOperationsHelper.DeleteDirectory(tempMediaLocation, true);

                    _logger.Info("Deleting text file: " + folder + "\\" + fileName);
                    DirectoryOperationsHelper.Delete(folder + "\\" + fileName);
                }
                else
                {
                    _logger.Info("No Data found for account Id: " + filter.AccountId);
                }
            }
            else
            {
                _logger.Info("No record found for " + account.Tag);
            }
        }
        private void WriteCsv(IEnumerable <GmsExcludedCustomerViewModel> modelData, string fileName)
        {
            _logger.Info("Writing CSV file " + fileName);

            if (DirectoryOperationsHelper.IsFileExist(fileName))
            {
                DirectoryOperationsHelper.Delete(fileName);
            }

            var fileWriter = new StreamWriter(fileName);

            try
            {
                var members = (typeof(GmsExcludedCustomerViewModel)).GetMembers();

                var header = new List <string>();

                foreach (var memberInfo in members)
                {
                    if (memberInfo.MemberType != MemberTypes.Property)
                    {
                        continue;
                    }

                    var propInfo = (memberInfo as PropertyInfo);

                    if (propInfo != null)
                    {
                        if (propInfo.PropertyType == typeof(FeedbackMessageModel))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }

                    var propertyName = memberInfo.Name;
                    var isHidden     = false;

                    var attributes = propInfo.GetCustomAttributes(false);

                    if (!attributes.IsNullOrEmpty())
                    {
                        foreach (var attribute in attributes)
                        {
                            if (attribute is HiddenAttribute)
                            {
                                isHidden = true;
                                break;
                            }
                            if (attribute is DisplayNameAttribute)
                            {
                                propertyName = (attribute as DisplayNameAttribute).DisplayName;
                            }
                        }
                    }

                    if (isHidden)
                    {
                        continue;
                    }

                    header.Add(propertyName);
                }

                fileWriter.WriteLine(string.Join(",", header.ToArray()));

                var sanitizer = new CSVSanitizer();


                foreach (var model in modelData)
                {
                    var values = new List <string>();
                    foreach (var memberInfo in members)
                    {
                        if (memberInfo.MemberType != MemberTypes.Property)
                        {
                            continue;
                        }

                        var propInfo = (memberInfo as PropertyInfo);
                        if (propInfo != null)
                        {
                            if (propInfo.PropertyType == typeof(FeedbackMessageModel))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }


                        bool            isHidden  = false;
                        FormatAttribute formatter = null;

                        var attributes = propInfo.GetCustomAttributes(false);
                        if (!attributes.IsNullOrEmpty())
                        {
                            foreach (var attribute in attributes)
                            {
                                if (attribute is HiddenAttribute)
                                {
                                    isHidden = true;
                                    break;
                                }
                                if (attribute is FormatAttribute)
                                {
                                    formatter = (FormatAttribute)attribute;
                                }
                            }
                        }

                        if (isHidden)
                        {
                            continue;
                        }
                        var obj = propInfo.GetValue(model, null);
                        if (obj == null)
                        {
                            values.Add(string.Empty);
                        }
                        else if (formatter != null)
                        {
                            values.Add(formatter.ToString(obj));
                        }
                        else
                        {
                            values.Add(sanitizer.EscapeString(obj.ToString()));
                        }
                    }

                    fileWriter.WriteLine(string.Join(",", values.ToArray()));
                }

                _logger.Info("CSV File Export was succesful!");
            }
            catch (Exception ex)
            {
                _logger.Error((string.Format("File Write: \n Error {0} \n Trace: {1} \n\n\n", ex.Message, ex.StackTrace)));
            }
            finally
            {
                fileWriter.Close();
                fileWriter.Dispose();
            }
        }
Exemplo n.º 13
0
        protected void DownloadZipFile(MediaLocation mediaLocation, string csvfileName)
        {
            var csvFilePath = mediaLocation.PhysicalPath + csvfileName;

            var response = Response;

            try
            {
                if (_sessionContext == null || _sessionContext.UserSession == null)
                {
                    _logger.Error("User Session is null while downloading report file: " + csvFilePath);
                    throw new Exception();
                }

                var userId        = _sessionContext.UserSession.UserId;
                var isPinRequired = false;
                var user          = _userRepository.GetUser(userId);
                var orgRoles      = _organizationRoleUserRepository.GetOrganizationRoleUserCollectionforaUser(userId);
                var defaultRole   = orgRoles.FirstOrDefault(oru => oru.RoleId == (long)user.DefaultRole);
                if (defaultRole != null)
                {
                    Role role = _roleRepository.GetByRoleId(defaultRole.RoleId);
                    isPinRequired = role.IsPinRequired;
                }
                var password = "";
                if (isPinRequired)
                {
                    var userSetting = _loginSettingRepository.Get(userId);
                    if (userSetting != null)
                    {
                        password = userSetting.DownloadFilePin;
                    }
                }

                var zipFilePath = _zipHelper.CreateZipOfSingleFile(csvFilePath, password);

                var fileName = Path.GetFileName(zipFilePath);
                if (fileName == null || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
                {
                    throw new InvalidFileNameException();
                }
                response.Clear();
                response.ClearHeaders();
                response.ContentType = "application/zip";
                response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.HtmlEncode(fileName.Replace(Environment.NewLine, "")));
                response.Cache.SetCacheability(HttpCacheability.NoCache);
                var buffer = DirectoryOperationsHelper.ReadAllBytes(zipFilePath);
                response.BinaryWrite(buffer);
            }
            catch (Exception ex)
            {
                _logger.Error("Error while creating zip file. CSV File Name :  " + csvFilePath + ". Message: " + ex.Message + " \n\t Stack Trace:" + ex.StackTrace);
            }
            finally
            {
                try
                {
                    DirectoryOperationsHelper.Delete(csvFilePath);
                }
                catch (Exception exception)
                {
                    _logger.Error("Error while deleting file. Name :  " + csvFilePath + ". Message: " + exception.Message + " \n\t Stack Trace:" + exception.StackTrace);
                }
                response.End();
            }
        }
        public void CreateZipFile()
        {
            try
            {
                if (_accountIds.IsNullOrEmpty())
                {
                    return;
                }
                var corporateAccounts = _corporateAccountRepository.GetByIds(_accountIds);
                foreach (var account in corporateAccounts)
                {
                    try
                    {
                        _logger.Info(string.Format("Creating zip for accountId {0} and account tag {1}. ", account.Id, account.Tag));

                        var fileName = account.FolderName.Replace("_", "") + "_DATA_" + DateTime.Today.ToString("MMyydd");

                        var sourceFile      = string.Format(_optumZipFolderDownloadFromPath, account.FolderName);
                        var destinationPath = string.Format(_optumZipFolderPostToPath, account.FolderName);

                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            destinationPath = string.Format(_monarchZipFolderPath, account.FolderName);
                            fileName        = account.FolderName + "_DATA_" + DateTime.Today.ToString("yyyyMMdd");
                        }

                        _logger.Info("Destination Path:" + destinationPath);

                        if (!DirectoryOperationsHelper.IsDirectoryExist(destinationPath))
                        {
                            Directory.CreateDirectory(destinationPath);
                        }

                        var destinationfile = destinationPath + "\\" + fileName + ".zip";

                        if (DirectoryOperationsHelper.IsFileExist(destinationfile))
                        {
                            DirectoryOperationsHelper.Delete(destinationfile);
                        }

                        var directoryToDeleteFrom = new DirectoryInfo(destinationPath);

                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            var zipFiles = directoryToDeleteFrom.GetFiles(account.FolderName + "_DATA_*.zip");

                            foreach (var file in zipFiles)
                            {
                                _logger.Info("Deleting zip file : " + file.Name);
                                file.Delete();
                            }
                        }
                        else
                        {
                            var fileNotToBeDelete = GetFileNotDeleted();

                            var zipFiles = directoryToDeleteFrom.GetFiles(account.FolderName.Replace("_", "") + "_DATA_*.zip");

                            foreach (var file in zipFiles)
                            {
                                if (fileNotToBeDelete.Any(x => file.Name.EndsWith(x)))
                                {
                                    continue;
                                }

                                _logger.Info("Deleting zip file : " + file.Name);
                                file.Delete();
                            }
                        }

                        _zipHelper.CreateZipFiles(sourceFile, destinationfile, true);


                        if (_monarchAccountIds.Contains(account.Id))
                        {
                            var sftpCridential = _sftpCridentialManager.Deserialize(_sftpResouceFilePath + account.Tag + ".xml");

                            try
                            {
                                ExportResultInSftp(fileName + ".zip", destinationfile, sftpCridential);
                            }
                            catch (Exception exception)
                            {
                                _logger.Error("message: " + exception.Message);
                                _logger.Error("stack trace: " + exception.StackTrace);
                            }

                            var archiveDestinationPath = string.Format(_monarchResultPdfArchive, account.FolderName);

                            DirectoryOperationsHelper.CreateDirectoryIfNotExist(archiveDestinationPath + "\\pdfs\\");

                            var sourceDir      = new DirectoryInfo(sourceFile + "/pdfs/");
                            var destinationDir = new DirectoryInfo(archiveDestinationPath + "\\pdfs\\");

                            DeepCopy(sourceDir, destinationDir);
                            Directory.Delete(sourceFile + "/pdfs/", true);
                        }

                        _logger.Info("Zip File Created");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Some Error occurred for Account Id " + account.Id + " Account Tag " + account.Tag);
                        _logger.Error("Message " + ex.Message);
                        _logger.Error("Stack Trace " + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Some Error occurred ");
                _logger.Error("Message " + ex.Message);
                _logger.Error("Stack Trace " + ex.StackTrace);
            }
        }