private List<LawMetadataBEO> GetFields(LawSyncDocumentDetail lawDocument, List<LawMetadataBEO> metaDataList, out bool isError)
        {
            isError = false;
            if (_jobParameter.MappingFields == null || !_jobParameter.MappingFields.Any()) return metaDataList;

            var document = GetDocumentDetails(lawDocument.DocumentReferenceId, _datasetCollectionId, out isError);

            foreach (var lawMappingField in _jobParameter.MappingFields)
            {
                var docField =
                    document.FieldList.FirstOrDefault(
                        f =>
                            f.FieldId.ToString(CultureInfo.InvariantCulture)
                                .Equals(lawMappingField.MappingFieldId));
                if (docField == null) continue;

               var datasetField=  _dataset.DatasetFieldList.FirstOrDefault(f => f.ID.ToString(CultureInfo.InvariantCulture)
                   .Equals(lawMappingField.MappingFieldId));
                var format=string.Empty;
                if (datasetField != null)
                {
                    format = datasetField.FieldType.DataFormat;
                }

                var metaData = new LawMetadataBEO
                               {
                                   Name = lawMappingField.Name,
                                   Id = lawMappingField.Id, //Not Required
                                   Type = lawMappingField.FieldType,
                                   Value = ConvertFieldValueIntoLawType(docField.FieldValue, lawMappingField.FieldType, format)
                               };

                metaDataList.Add(metaData);
            }
            return metaDataList;
        }
        private DocumentConversionLogBeo GetDocumentProcessStateInformation(LawSyncDocumentDetail lawDocument, int state)
        {
            var documentProcessState = new DocumentConversionLogBeo
            {
                JobRunId = _lawSyncJobId,
                ProcessJobId = WorkAssignment.JobId,

                DocumentId = lawDocument.DocumentReferenceId,
                CollectionId = _datasetCollectionId,

                MetadataSyncStatus = state,
                Status = EVRedactItErrorCodes.Failed, 
                ReasonId =  (int)Constants.LawSynProcessStateErrorCodes.MetadataSyncFailure,

                ModifiedDate = DateTime.UtcNow
            };
            return documentProcessState;
        }
        private void ConstructLawSyncDocument(IEnumerable<ReconversionDocumentBEO> reprocessDocumentList)
        {
            #region Produce Image
            List<FilteredDocumentBusinessEntity> imagingDocuments = null;
            if (_lawSyncJobParameter.IsProduceImage)
            {
                var documentsSelection = new List<DocumentsSelectionBEO>
                                         {
                                             _lawSyncJobParameter.DocumentsSelection,
                                             _lawSyncJobParameter.ImageDocumentsSelection
                                         };
                imagingDocuments = LawSyncSearchHelper.GetDocuments(documentsSelection, _dcnFieldName, _lawSyncJobParameter.CreatedBy);
            }
            #endregion

            var runningDocCount = 0;
            var lawDocumentsList = new List<LawSyncDocumentDetail>();
            var documentProcessStateList = new List<DocumentConversionLogBeo>();
            _logInfoList = new List<JobWorkerLog<LawSyncLogInfo>>();
            foreach (var reprocessDocument in reprocessDocumentList)
            {
                _documentCorrelationId++;
                runningDocCount++;
                if (runningDocCount > Constants.BatchSize)
                {
                    runningDocCount = 0;
                    UpdateDcoumentProcessState(documentProcessStateList);
                    Send(lawDocumentsList);
                    lawDocumentsList = new List<LawSyncDocumentDetail>(); //Clear document List
                      documentProcessStateList = new List<DocumentConversionLogBeo>(); //Clear document process state List
                }
                var lawDocument = new LawSyncDocumentDetail
                                  {
                                      DocumentReferenceId = reprocessDocument.DocumentId,
                                      DocumentControlNumber = reprocessDocument.DCNNumber,
                                      CorrelationId = _documentCorrelationId

                                  };

                if (_lawSyncJobParameter.IsProduceImage && imagingDocuments != null && imagingDocuments.Any())
                {
                    lawDocument.IsImaging = imagingDocuments.Exists(y => y.DCN.Equals(lawDocument.DocumentControlNumber));
                }
                else
                {
                    //Document not part of imaging subset excluded for imaging.
                    lawDocument.IsImaging = false;
                }


                var field =
                    DocumentBO.GetDocumentFieldById(
                        _lawSyncJobParameter.MatterId.ToString(CultureInfo.InvariantCulture), _dataset.CollectionId,
                        lawDocument.DocumentReferenceId, _lawFieldId);
                if (field != null && !string.IsNullOrEmpty(field.FieldValue))
                    lawDocument.LawDocumentId = Convert.ToInt32(field.FieldValue);

                if (lawDocument.IsImaging)
                {
                    _volumeDocumentCount++;
                    var documentPagesCount = GetPageCountForImages(_lawSyncJobParameter.MatterId,
                        _dataset.RedactableDocumentSetId, lawDocument.DocumentReferenceId);
                    if (_volumeDocumentCount > VolumeMaximumDocumentCount)
                    {
                        _volumeDocumentCount = 0;
                        _volumeCount++;
                        _volumeFolderName = LawVolumeHelper.CreateVolumeFolder(_jobEVImagesDirectory, _volumeCount);
                        _volumeDocumentPagesCount = 0;
                    }
                    lawDocument.ImagesFolderPath = _volumeFolderName;
                    lawDocument.ImageStartingNumber = _volumeDocumentPagesCount;
                    _volumeDocumentPagesCount = _volumeDocumentPagesCount + documentPagesCount;
                }
                if (lawDocument.LawDocumentId > 0)
                {
                    lawDocumentsList.Add(lawDocument);
                }
                else
                {
                    ConstructLog(lawDocument.LawDocumentId, lawDocument.CorrelationId, lawDocument.DocumentControlNumber, Constants.LawSyncDocumentNotAvailable);
                }
                documentProcessStateList.Add(GetDocumentProcessStateInformation(lawDocument));
            }

            if (documentProcessStateList.Any())
            {
                UpdateDcoumentProcessState(documentProcessStateList);
            }

            if (lawDocumentsList.Any())
            {
                Send(lawDocumentsList);
            }
            if (_logInfoList.Any())
            {
                SendLogPipe(_logInfoList);
            }
        }
        private void GetTags(LawSyncDocumentDetail lawDocument, List<LawMetadataBEO> metaDataList, out bool isError)
        {
            isError = false;
            if (_jobParameter.MappingTags == null || !_jobParameter.MappingTags.Any()) return;
            var documentTag = GetDocumentTags(lawDocument.DocumentReferenceId, _datasetCollectionId, out isError);
            foreach (var lawMappingTag in _jobParameter.MappingTags)
            {
                var docTag =
                    documentTag.FirstOrDefault(
                        f =>
                            f.TagId.ToString(CultureInfo.InvariantCulture)
                                .Equals(lawMappingTag.MappingTagId));

                var metaData = new LawMetadataBEO
                               {
                                   Name = lawMappingTag.Name,
                                   Id = lawMappingTag.Id, //Not Required
                                   Value = (docTag != null),
                                   IsTag = true
                               };

                metaDataList.Add(metaData);
            }
        }
        /// <summary>
        /// Handle Image Conversion Failure
        /// </summary>
        private void HandleConversionImageFailureState(LawSyncDocumentDetail lawImagingDocument, RedactItHeartbeatWatcher.DocumentStatus documentStatus, bool isTimeOut)
        {
            SafeDeleteFolder(lawImagingDocument.DocumentExtractionPath);

            // Bug 169138: When conversion time out, Job log table display the error message "Failure in image conversion". It should display "Conversion timeout".
            string errorMessage = Constants.LawSyncFailureinConversionMessage;
            if (isTimeOut)
            {
                errorMessage = Constants.LawSyncFailureinConversionTimeOutMessage;
            }
            Tracer.Error("Image conversion error: {0}", errorMessage);
            ConstructLog(lawImagingDocument.LawDocumentId, lawImagingDocument.CorrelationId,
                lawImagingDocument.DocumentControlNumber, errorMessage, lawImagingDocument.RedactItHeartBeatFilePath, lawImagingDocument.ImagesFolderPath);
             

            IncreaseProcessedDocumentsCount(1); // Failed document counted as processed
           
            if (string.IsNullOrEmpty(documentStatus.ErrorReason))
            {
                documentStatus.ErrorReason = EVRedactItErrorCodes.UnKnownConversionFailure;
            }
            //Filling error details in ProcessSet table for future use
            var documentProcessState = GetDocumentProcessStateInformationForImageConversion(lawImagingDocument,
                documentStatus.ErrorReason);
            documentProcessState.ErrorDetails = documentStatus.ErrorMessage;
            _documentProcessStateList.Add(documentProcessState);
            //Handle partially converted documents
            RenameAndSetImagesInDocument(lawImagingDocument);
        }
        private DocumentConversionLogBeo GetDocumentProcessStateInformation(LawSyncDocumentDetail lawDocument, int status)
        {
            var documentProcessState = new DocumentConversionLogBeo
                                       {
                JobRunId = _lawSyncJobId,
                ProcessJobId = WorkAssignment.JobId,

                DocumentId = lawDocument.DocumentReferenceId,
                CollectionId = _datasetCollectionId,
                ConversionStatus = status,
                Status = EVRedactItErrorCodes.Failed, //default state

                ModifiedDate = DateTime.UtcNow
            };

            //Category Reason
            if (documentProcessState.ConversionStatus == (int)LawSyncProcessState.Failed)
            {
                documentProcessState.ReasonId = (int)Constants.LawSynProcessStateErrorCodes.ImageConversionFailure;
            }
            else
            {
                documentProcessState.ReasonId = (int)Constants.LawSynProcessStateErrorCodes.Successful;
            }
            return documentProcessState;
        }
        private DocumentConversionLogBeo GetDocumentProcessStateInformationForImageConversion(
            LawSyncDocumentDetail lawDocument, string errorReason = null)
        {
            var documentProcessState = new DocumentConversionLogBeo
                                       {
                                           JobRunId = _lawSyncJobId,
                                           ProcessJobId = WorkAssignment.JobId,

                                           DocumentId = lawDocument.DocumentReferenceId,
                                           CollectionId = _datasetCollectionId,

                                           Status = EVRedactItErrorCodes.Failed,

                                           ErrorReason = errorReason,

                                           ConversionStatus = (int) LawSyncProcessState.Failed,
                                           ImageSyncStatus = (int) LawSyncProcessState.NotStarted,
                                           ReasonId =(int) Constants.LawSynProcessStateErrorCodes.ImageConversionFailure,

                                           ModifiedDate = DateTime.UtcNow
                                       };

            if (!string.IsNullOrEmpty(errorReason) && errorReason.Length > 60)  //To set common conversion error when conversion reason was not generic
            {
                documentProcessState.ErrorReason = EVRedactItErrorCodes.UnKnownConversionFailure;
            }
            return documentProcessState;
        }
        /// <summary>
        /// Get document process state information
        /// </summary>
        private DocumentConversionLogBeo GetDocumentProcessStateInformation(LawSyncDocumentDetail lawDocument)
        {
            var documentProcessState = new DocumentConversionLogBeo
                                       {
                                           ProcessJobId = WorkAssignment.JobId,
                                           JobRunId = WorkAssignment.JobId,

                                           DocumentId = lawDocument.DocumentReferenceId,
                                           CollectionId = _dataset.CollectionId,
                                           DCN = lawDocument.DocumentControlNumber,
                                           CrossReferenceId =
                                               lawDocument.LawDocumentId.ToString(CultureInfo.InvariantCulture),
                                         
                                           MetadataSyncStatus = (int) LawSyncProcessState.NotStarted,
                                           ReasonId = (int) Constants.LawSynProcessStateErrorCodes.MetadataSyncFailure,
                                           Status =  EVRedactItErrorCodes.Failed, //Default state

                                           ModifiedDate = DateTime.UtcNow,
                                           CreatedDate = DateTime.UtcNow
                                       };

            if (!lawDocument.IsImaging) return documentProcessState;
            documentProcessState.ImageSyncStatus = (int) LawSyncProcessState.NotStarted;
            documentProcessState.ConversionStatus = (int) LawSyncProcessState.NotStarted;
            return documentProcessState;
        }
 /// <summary>
 /// Update Images in Law
 /// </summary>
 /// <param name="document"></param>
 private void UpdateDocumentImageInLaw(LawSyncDocumentDetail document)
 {
     var lawDocumentUpdate = new LawDocumentBEO
                             {
                                 LawDocId = document.LawDocumentId,
                                 ImagePaths = document.ProducedImages
                             };
     _lawEvAdapter.UpdateLawImagePaths(lawDocumentUpdate);
     _documentProcessStateList.Add(GetDocumentProcessStateInformationForImageSync(document,
         (int) LawSyncProcessState.Completed));
 }
        private DocumentConversionLogBeo GetDocumentProcessStateInformationForImageSync(
            LawSyncDocumentDetail lawDocument, int state)
        {
            var documentProcessState = new DocumentConversionLogBeo
                                       {
                                           JobRunId = _lawSyncJobId,
                                           ProcessJobId = WorkAssignment.JobId,

                                           DocumentId = lawDocument.DocumentReferenceId,
                                           CollectionId = _datasetCollectionId,

                                           ConversionStatus = (int) LawSyncProcessState.Completed,
                                           ImageSyncStatus = state,

                                           ModifiedDate = DateTime.UtcNow
                                       };
            //Category Reason
            if (state == (int)LawSyncProcessState.Completed && !lawDocument.IsErrorOnSyncMetadata)
            {
                documentProcessState.ReasonId = (int)Constants.LawSynProcessStateErrorCodes.Successful;
            }
            else if (state == (int)LawSyncProcessState.Failed)
            {
                documentProcessState.ReasonId = (int)Constants.LawSynProcessStateErrorCodes.ImageSyncFailure;
            }
            else
            {
                documentProcessState.ReasonId = (int)Constants.LawSynProcessStateErrorCodes.MetadataSyncFailure;
            }

            //Status
            if (state == (int)LawSyncProcessState.Completed && !lawDocument.IsErrorOnSyncMetadata)
            {
                documentProcessState.Status = EVRedactItErrorCodes.Completed; 
            }
            else
            {
                documentProcessState.Status = EVRedactItErrorCodes.Failed;
            }
           
            return documentProcessState;
        }
        /// <summary>
        /// Handle Image Not Found
        /// </summary>
        private bool HandleConversionImageNotFoundState(LawSyncDocumentDetail lawImagingDocument, RedactItHeartbeatWatcher.DocumentStatus documentStatus,
            List<LawSyncDocumentDetail> documentNotReady)
        {
            if (!lawImagingDocument.ConversionEnqueueTime.HasValue)
            {
                lawImagingDocument.ConversionEnqueueTime = DateTime.UtcNow;
            }
            if (DateTime.UtcNow - lawImagingDocument.ConversionEnqueueTime >
                _documentConverisonGlobalTimeout)
            {
                documentStatus.DocumentState = RedactItHeartbeatWatcher.DocumentStateEnum.Failure;
                documentStatus.ErrorMessage = Constants.GlobalDocumentconversionTimeoutMessage;

                Tracer.Trace("Global Conversion Timeout for Law document id - {0} ,dcn {1},collection id - {2} , HeartBeatFile {3} and Job Run Id {4}",
                    lawImagingDocument.LawDocumentId, lawImagingDocument.DocumentControlNumber,
                    lawImagingDocument.RedactItHeartBeatFilePath,
                    PipelineId);
                return false;
            }
            documentNotReady.Add(lawImagingDocument);
            return true;
        }
        /// <summary>
        /// Handle Image Conversion Not Ready
        /// </summary>
        private bool HandleConversionImageNotReadyState(LawSyncDocumentDetail lawImagingDocument, RedactItHeartbeatWatcher.DocumentStatus documentStatus,
            List<LawSyncDocumentDetail> documentNotReady)
        {
            if (!lawImagingDocument.ConversionStartTime.HasValue)
            {
                lawImagingDocument.ConversionStartTime = DateTime.UtcNow;
            }            
            if (DateTime.UtcNow - lawImagingDocument.ConversionStartTime > _documentConversionTimeout)
            {
                documentStatus.DocumentState = RedactItHeartbeatWatcher.DocumentStateEnum.Failure;
                documentStatus.ErrorMessage = Constants.DocumentconversionTimeoutMessage;

                Tracer.Error("Conversion Timeout for Law document id - {0} ,dcn {1} , HeartBeatFile {2}, timeoutValue: {3}",
                   lawImagingDocument.LawDocumentId, lawImagingDocument.DocumentControlNumber,
                    lawImagingDocument.RedactItHeartBeatFilePath, _documentConversionTimeout.TotalSeconds);
                return false;
            }
            documentNotReady.Add(lawImagingDocument);
            return true;
        }
        /// <summary>
        /// Handle Image Conversion Sucesss
        /// </summary>
        private void HandleConversionImageSucessState(List<LawSyncDocumentDetail> documentReady, LawSyncDocumentDetail lawImagingDocument)
        {
            try
            {
                documentReady.Add(lawImagingDocument);
                SafeDeleteFolder(lawImagingDocument.DocumentExtractionPath);
                SafeDeleteFile(lawImagingDocument.RedactItHeartBeatFilePath);            
                RenameAndSetImagesInDocument(lawImagingDocument);
                UpdateDocumentImageInLaw(lawImagingDocument);
            }
            catch (Exception ex)
            {
                ConstructLog(lawImagingDocument.LawDocumentId, lawImagingDocument.CorrelationId, lawImagingDocument.DocumentControlNumber,
                    Constants.LawSyncFailureinSyncImageMessage);
                _documentProcessStateList.Add(GetDocumentProcessStateInformationForImageSync(lawImagingDocument,
                    (int) LawSyncProcessState.Failed));

                ex.AddDbgMsg("Law Document Id:{0}", lawImagingDocument.LawDocumentId);
                ex.Trace().Swallow();
                ReportToDirector(ex);
            }
        }
            void SetMetadataForDcoument(LawSyncDocumentDetail lawDocument)
        {
            try
            {
                var metaDataList = new List<LawMetadataBEO>();
                //1) Get Fields
                bool isErrorInGetFields;
                metaDataList = GetFields(lawDocument, metaDataList, out isErrorInGetFields);
                //2) Get Tag
                bool isErrorInGetTags;
                GetTags(lawDocument, metaDataList, out isErrorInGetTags);
                //3) Law sync Tag 
                var lawSyncTag = new LawMetadataBEO
                                 {
                                     Name = _jobParameter.LawSyncTagName,
                                     Value = true,
                                     IsTag = true
                                 };
                metaDataList.Add(lawSyncTag);
                lawDocument.MetadataList = metaDataList;

                if (isErrorInGetFields || isErrorInGetTags)
                {
                    ConstructLog(lawDocument.LawDocumentId, lawDocument.CorrelationId, lawDocument.DocumentControlNumber,
                        Constants.LawSyncFailureinGetMetadataMessage);
                    _documentProcessStateList.Add(GetDocumentProcessStateInformation(lawDocument, (int)LawSyncProcessState.Failed));
                    lawDocument.IsErrorOnGetMetadata = true;
                }

            }
            catch (Exception ex)
            {
                ConstructLog(lawDocument.LawDocumentId, lawDocument.CorrelationId, lawDocument.DocumentControlNumber,
                    Constants.LawSyncFailureinGetMetadataMessage);
                _documentProcessStateList.Add(GetDocumentProcessStateInformation(lawDocument, (int)LawSyncProcessState.Failed));
                lawDocument.IsErrorOnGetMetadata = true;
                ex.AddDbgMsg("Law Document Id:{0}", lawDocument.LawDocumentId);
                ex.Trace().Swallow();
                ReportToDirector(ex);
            }
        }
 private void RenameAndSetImagesInDocument(LawSyncDocumentDetail lawDocument)
 {
     try
     {
         var lawDocumentId = lawDocument.DocumentControlNumber;
         var files =
             new DirectoryInfo(lawDocument.ImagesFolderPath).GetFiles(
                 string.Format("{0}{1}*", lawDocumentId,Constants.RedactItPagingNameFormat));
         if (!files.Any()) return;
         var convertedImages = new List<ConvertedImage>(); // hold the list of converted iamges. 
         foreach (var file in files)
         {
             if (String.IsNullOrEmpty(file.Name)) continue;
             var fileExtenstion = Path.GetExtension(file.Name);
             var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.Name);
             var currentPage = fileNameWithoutExtension.Replace(lawDocumentId, "").Replace(Constants.RedactItPagingNameFormat, "");
             int pageNumber;
             if (!int.TryParse(currentPage,
                 out pageNumber))
             {
                 continue;
             }
             var imageStartingNumber = (lawDocument.ImageStartingNumber + 1) + pageNumber;
             var newFileName = string.Format("{0:D3}", imageStartingNumber) + fileExtenstion;
             var image = Path.Combine(lawDocument.ImagesFolderPath, newFileName);
             File.Move(file.FullName, image);
             var evImageRelativePath = image.Replace(_imageArchiveDirectory, string.Empty);
             evImageRelativePath = evImageRelativePath.StartsWith(@"\") ? evImageRelativePath.Remove(0, 1) : evImageRelativePath;
             convertedImages.Add(new ConvertedImage { PageNo = pageNumber, RelativePath = evImageRelativePath });
         }
         // DEVBug 169433: Page order mess up for LAW Sync reprocess. For example the first page in LAW is not the first page in EV NNV viewer,
         // e.g. the first page is 701.tif instead of 001.tif. 
         // To solve this, we need to sort the image by page Number
         var imagePaths = convertedImages.OrderBy(o => o.PageNo).Select(o => o.RelativePath).ToList();
         if (lawDocument.ProducedImages == null)
         {
             lawDocument.ProducedImages = new List<string>();
         }
         lawDocument.ProducedImages.AddRange( imagePaths );
     }
     catch (Exception ex)
     {
         //continue the image process with out rename images
         ex.Trace().Swallow();
         ReportToDirector(ex);
     }
 }
        /// <summary>
        /// Construct LawSync document
        /// </summary>
        private void ConstructLawSyncDocument(IEnumerable<FilteredDocumentBusinessEntity> resultDocuments)
        {
            var runningDocCount = 0;
            var lawDocumentsList=new List<LawSyncDocumentDetail>();
            var documentProcessStateList = new List<DocumentConversionLogBeo>();
            _logInfoList = new List<JobWorkerLog<LawSyncLogInfo>>();
            foreach (var doc in resultDocuments)
            {
                _documentCorrelationId++;
                runningDocCount++;
                if (runningDocCount > Constants.BatchSize)
                {
                    runningDocCount = 0;
                    InsertDcoumentProcessState(documentProcessStateList);
                    Send(lawDocumentsList);
                    lawDocumentsList = new List<LawSyncDocumentDetail>(); //Clear document List
                    documentProcessStateList = new List<DocumentConversionLogBeo>(); //Clear document process state List
                }
               
                var lawDocument=new LawSyncDocumentDetail
                                {
                                    DocumentReferenceId = doc.Id,
                                    DocumentControlNumber = doc.DCN,
                                    IsImaging = !doc.IsExclude,
                                    CorrelationId = _documentCorrelationId

                                };
                var field = doc.OutPutFields.FirstOrDefault(f => f.Name == EVSystemFields.LawDocumentId);
                if (field != null && !string.IsNullOrEmpty(field.Value))
                      lawDocument.LawDocumentId = Convert.ToInt32(field.Value);
              
                //To fix upgrade issue from earlier version to 3.0 version. Law document id(LawDocumentId) not coming part of search result.
                if(lawDocument.LawDocumentId<=0) 
                {
                    var lawField = DocumentBO.GetDocumentFieldById(
                       _jobParameter.MatterId.ToString(CultureInfo.InvariantCulture), _dataset.CollectionId,
                       lawDocument.DocumentReferenceId, _lawFieldId);
                    if (lawField != null && !string.IsNullOrEmpty(lawField.FieldValue))
                    {
                        lawDocument.LawDocumentId = Convert.ToInt32(lawField.FieldValue);
                    }
                }

                if (lawDocument.IsImaging)
                {
                    _volumeDocumentCount++;
                    var documentPagesCount = GetPageCountForImages(_jobParameter.MatterId,
                        _dataset.RedactableDocumentSetId, lawDocument.DocumentReferenceId);
                    if (_volumeDocumentCount > VolumeMaximumDocumentCount)
                    {
                        _volumeDocumentCount = 0;
                        _volumeCount++;
                        _volumeFolderName = LawVolumeHelper.CreateVolumeFolder(_jobEVImagesDirectory, _volumeCount);
                        _volumeDocumentPagesCount = 0;
                    }
                    lawDocument.ImagesFolderPath = _volumeFolderName;
                    lawDocument.ImageStartingNumber = _volumeDocumentPagesCount;
                    _volumeDocumentPagesCount = _volumeDocumentPagesCount + documentPagesCount;
                }

                if (lawDocument.LawDocumentId>0)
                {
                    lawDocumentsList.Add(lawDocument);
                }
                else
                {
                    ConstructLog(lawDocument.LawDocumentId, lawDocument.CorrelationId, lawDocument.DocumentControlNumber, Constants.LawSyncDocumentNotAvailable);
                }
                documentProcessStateList.Add(GetDocumentProcessStateInformation(lawDocument));
            }

            if (documentProcessStateList.Any())
            {
                InsertDcoumentProcessState(documentProcessStateList);
            }

            if (lawDocumentsList.Any())
            {
                Send(lawDocumentsList);
            }

            if (_logInfoList.Any())
            {
                SendLogPipe(_logInfoList);
            }
        }
        private void SendDocumentForImaging(LawSyncDocumentDetail document)
        {
            int conversionStatus = (int)LawSyncProcessState.InProgress;
            try
            {

                var queryString = new StringBuilder();
                var sourceExtractionPath = Path.Combine(_datasetExtractionPath, Guid.NewGuid().ToString(),
                    Constants.SourceKeyword);
                Directory.CreateDirectory(sourceExtractionPath);

                document.DocumentExtractionPath = sourceExtractionPath; //Need to be deleted.

                //1)Set source file(xdl,zdl) & Markup xml
                var source = CreateSourceFiles(sourceExtractionPath, document.DocumentReferenceId);
                if (string.IsNullOrEmpty(source))
                {
                    document.IsImagesXdlAvailable = false;
                    _documentProcessStateList.Add(GetDocumentProcessStateInformation(document, (int)LawSyncProcessState.Failed));
                    ConstructLog(document.LawDocumentId, document.CorrelationId, document.DocumentControlNumber, Constants.LawSyncMissingImageMessage);
                    return;
                }
                document.IsImagesXdlAvailable = true;
                queryString.Append(source);

                //2)Set Image Folder
                queryString.Append(Constants.QueryStringTargetPrefix);
                queryString.Append(HttpUtility.UrlEncode(document.ImagesFolderPath));//Target folder for redact it to generate pdf

                
                //3)Set Produced Image File name
                var fileName = document.DocumentControlNumber + Constants.Tifextension;
                queryString.Append(Constants.QueryStringDestinationFileName);
                queryString.Append(fileName);

                //4)Set Hearbeat file path-  Use to get the status of the document. The extension is .txt
                var heartBeatFile = Path.Combine(document.ImagesFolderPath,
                    string.Format("{0}{1}{2}",document.DocumentControlNumber,Constants.HeartbeatFileName,Constants.TextFileExtension));
                queryString.Append(Constants.QueryStringHeartBeatFileName);
                queryString.Append(HttpUtility.UrlEncode(heartBeatFile));
                document.RedactItHeartBeatFilePath = heartBeatFile;

                //5)Set Image Format(.Tiff)
                queryString.Append(Constants.QueryStringOutputFormatPrefix);
                queryString.Append(Constants.TifKeyword);

                //6)Set Image Color settings
                if (_jobParameter.TiffImageColor == TiffImageColors.One) //tiff monochrome 
                {
                    queryString.Append(Constants.QueryStringTiffMonochromePrefix);
                    queryString.Append(Constants.TrueString);
                    queryString.Append(Constants.QueryStringTifDPI);
                }
                else //tiff colour
                {
                    var tiffBpp = ((int) _jobParameter.TiffImageColor).ToString(CultureInfo.InvariantCulture);
                    queryString.Append(Constants.QueryStringTiffBppPrefix);
                    queryString.Append(tiffBpp);
                    queryString.Append(Constants.QueryStringTifDPI);
                }

                //7)Set Redact-It Timeout
                queryString.Append(Constants.StepTimeout);
                queryString.Append(_redactitTimeout);

                //8)Set One images per page
                queryString.Append(Constants.QueryStringOneFilePerPagePrefix);
                queryString.Append(Constants.TrueString);

                
               //9)Set Redact It Job priority
                queryString.Append(Constants.QueryStringPriority);
               queryString.Append(((int)_jobParameter.ConversionPriority));

                //10 Redact-It callback Url
               queryString.Append(Constants.QueryStringNotificationUrlPrefix);
               queryString.Append(_redactitCallbackUrl);

               queryString.Append(Constants.PublishBlankPagesQueryString);
               queryString.Append(CmgServiceConfigBO.GetServiceConfigurationsforConfig(Constants.PublishBlankPages));

                PushDocumentToQueueServer(queryString, document.LawDocumentId, heartBeatFile);
            }
            catch (Exception ex)
            {
                ConstructLog(document.LawDocumentId, document.CorrelationId,document.DocumentControlNumber ,Constants.LawSyncImageSendFailureMessage);
                ex.AddDbgMsg("Law Document Id:{0}", document.LawDocumentId);
                ex.Trace().Swallow();
                ReportToDirector(ex);
                conversionStatus = (int)LawSyncProcessState.Failed;
            }

            _documentProcessStateList.Add(GetDocumentProcessStateInformation(document, conversionStatus));
        }
        private DocumentConversionLogBeo GetDocumentProcessStateInformation(LawSyncDocumentDetail lawDocument, int state)
        {
            var documentProcessState = new DocumentConversionLogBeo
                                       {
                                           JobRunId = _lawSyncJobId,
                                           ProcessJobId = WorkAssignment.JobId,

                                           DocumentId = lawDocument.DocumentReferenceId,
                                           CollectionId = _datasetCollectionId,

                                           MetadataSyncStatus = state,
                                           Status = EVRedactItErrorCodes.Failed, //default state

                                           ModifiedDate = DateTime.UtcNow
                                       };

            //Category Reason
            if (state == (int) LawSyncProcessState.Failed)
            {
                documentProcessState.ReasonId = (int) Constants.LawSynProcessStateErrorCodes.MetadataSyncFailure;
            }
            else if (lawDocument.IsImaging && !lawDocument.IsImagesXdlAvailable)
            {
                documentProcessState.ReasonId = (int)Constants.LawSynProcessStateErrorCodes.ImageConversionFailure;
            }
            else
            {
                documentProcessState.ReasonId = (int)Constants.LawSynProcessStateErrorCodes.Successful;
            }


            if (lawDocument.IsImaging) return documentProcessState;

            //Status
            switch (state)
            {
                case (int) LawSyncProcessState.Completed:
                    documentProcessState.Status = EVRedactItErrorCodes.Completed;
                    break;
                case (int) LawSyncProcessState.Failed:
                    documentProcessState.Status = EVRedactItErrorCodes.Failed;
                    break;
            }
            return documentProcessState;
        }
        private void CheckConversionStateAndSyncImages(LawSyncDocumentDetail lawImagingDocument, List<LawSyncDocumentDetail> documentNotReady,
            List<LawSyncDocumentDetail> documentReady)
        {
            try
            {

                if (!lawImagingDocument.IsImagesXdlAvailable) return;
                var documentStatus =
                    RedactItHeartbeatWatcher.CheckDocumentState(lawImagingDocument.RedactItHeartBeatFilePath, 1);
                switch (documentStatus.DocumentState)
                {
                    case RedactItHeartbeatWatcher.DocumentStateEnum.NotFound:
                        if (!HandleConversionImageNotFoundState(lawImagingDocument, documentStatus, documentNotReady))
                        {
                            // timeout
                            // Bug 169138: When conversion time out, Job log table display the error message "Failure in image conversion". It should display "Conversion timeout".
                            HandleConversionImageFailureState(lawImagingDocument, documentStatus, true); // timeout
                        }
                        break;
                    case RedactItHeartbeatWatcher.DocumentStateEnum.NotReady:
                        if (!HandleConversionImageNotReadyState(lawImagingDocument, documentStatus, documentNotReady))
                        {
                            // timeout
                            // Bug 169138: When conversion time out, Job log table display the error message "Failure in image conversion". It should display "Conversion timeout".
                            HandleConversionImageFailureState(lawImagingDocument, documentStatus, true); // timeout
                        }
                        break;
                    case RedactItHeartbeatWatcher.DocumentStateEnum.Success:
                        HandleConversionImageSucessState(documentReady, lawImagingDocument);
                        break;
                    case RedactItHeartbeatWatcher.DocumentStateEnum.Failure:
                        HandleConversionImageFailureState(lawImagingDocument, documentStatus, false); // not timeout
                        break;
                }
            }
            catch (Exception ex)
            {
                ex.AddDbgMsg("Law Document Id:{0}", lawImagingDocument.LawDocumentId);
                ex.Trace().Swallow();
                ReportToDirector(ex);
            }
        }