protected override bool ProcessMessage(EmailMessage message) { // Determine whether this is the kind of message we're looking for if (message.Subject.StartsWith(_subjectStart, StringComparison.OrdinalIgnoreCase)) { try { // Extract the file prefix from the body ScanFilePrefix filePrefix = ExtractFileName(message.Body); // Create the log for this email DigitalSendJobNotificationLogger log = new DigitalSendJobNotificationLogger(); log.FilePrefix = filePrefix.ToString(); log.SessionId = filePrefix.SessionId; log.NotificationResult = message.Subject.Replace(_subjectStart, ""); log.NotificationDestination = EmailAddress; log.NotificationReceivedDateTime = message.DateTimeReceived; new DataLogger(GetLogServiceHost(filePrefix.SessionId)).Submit(log); // Success - the service can clean up the email. return(true); } catch { // If anything goes wrong, return false so that the service will leave // the email alone. return(false); } } else { return(false); } }
private string GetSessionId(IDataRecord record) { // See if we can use the name of the delivered file object result = record["DeliveredFileName"]; if (result != null) { string fileName = result.ToString(); if (ScanFilePrefix.MatchesPattern(fileName)) { ScanFilePrefix prefix = ScanFilePrefix.Parse(fileName); return(prefix.SessionId); } } // See if we can use the fax number result = record["FaxNumber"]; if (result != null) { try { ScanFilePrefix prefix = ScanFilePrefix.ParseFromFax(result.ToString(), "u"); return(prefix.SessionId); } catch (FormatException) { // Wrong format - do nothing } } // Use the last session we saw return(_sessionId); }
private static ScanFilePrefix ExtractFileName(string body) { string faxCode = string.Empty; string user = string.Empty; string line; char[] space = new char[] { ' ' }; using (StringReader reader = new StringReader(body)) { while ((line = reader.ReadLine()) != null) { if (line.Contains("User:"******"\\")) { user = user.Substring(user.IndexOf('\\') + 1); } } else if (line.Contains("-- Destination", StringComparison.OrdinalIgnoreCase)) { // The destination info is on the next line. line = reader.ReadLine(); faxCode = line.Split(space, StringSplitOptions.RemoveEmptyEntries)[0]; } } } return(ScanFilePrefix.ParseFromFax(faxCode, user)); }
private static ScanFilePrefix ExtractFileName(string hpfFile) { string faxCode = string.Empty; string user = string.Empty; foreach (string line in File.ReadLines(hpfFile)) { if (!string.IsNullOrEmpty(line)) { string[] parts = line.Split(' '); switch (parts[0]) { case "##UserName": user = parts[1]; break; case "##dial": faxCode = parts[1]; break; } } } return(ScanFilePrefix.ParseFromFax(faxCode, user)); }
private static void CreateNotificationFile(string hpfFile, ScanFilePrefix filePrefix) { using (StreamWriter file = new StreamWriter(Path.ChangeExtension(hpfFile, "000"))) { file.WriteLine("Status: OK"); file.WriteLine("Fax_number: " + filePrefix.ToFaxCode()); } }
private void ProcessDocument(SharePointDocument document, string filePath) { TraceFactory.Logger.Debug("Found file: " + document.FileName); try { string fileName = Path.GetFileName(filePath); ScanFilePrefix filePrefix = ScanFilePrefix.Parse(fileName); // Create the log for this file DigitalSendJobOutputLogger log = new DigitalSendJobOutputLogger(fileName, filePrefix.ToString(), filePrefix.SessionId); log.FileSentDateTime = document.Created.LocalDateTime; log.FileLocation = $@"{_library.SiteUrl.Host}\{_library.Name}"; // Validate and analyze the file OutputProcessor processor = new OutputProcessor(filePath); ValidationResult result = null; Retry.WhileThrowing( () => result = processor.Validate(Configuration), 10, TimeSpan.FromSeconds(2), new List <Type>() { typeof(IOException) }); // If the validation failed, there is a small chance that the HPS file arrived // a little later than the PDF and didn't get downloaded at the same time. // Check the server to see if that's the case - if so, run the validation again if (!result.Succeeded && result.Message.Contains("metadata", StringComparison.OrdinalIgnoreCase)) { if (FindMetadataFile(document)) { result = processor.Validate(Configuration); } } DocumentProperties properties = processor.GetProperties(); log.FileSizeBytes = properties.FileSize; log.PageCount = properties.Pages; log.SetErrorMessage(result); // Clean up the file processor.ApplyRetention(Configuration, result.Succeeded); // Send the output log new DataLogger(GetLogServiceHost(filePrefix.SessionId)).Submit(log); } catch (IOException ex) { LogProcessFileError(filePath, ex); } catch (FormatException ex) { LogProcessFileError(filePath, ex); } }
/// <summary> /// Initializes a new instance of the <see cref="DigitalSendJobOutputLogger"/> class. /// </summary> /// <param name="filePrefix">The scan file prefix to be used.</param> /// <param name="extension">The file extension.</param> public DigitalSendJobOutputLogger(ScanFilePrefix filePrefix, string extension) : this() { if (filePrefix == null) { throw new ArgumentNullException("filePrefix"); } FileName = Path.ChangeExtension(filePrefix.ToString(), extension); FilePrefix = filePrefix.ToString(); SessionId = filePrefix.SessionId; }
protected ScanActivityManager(PluginExecutionData executionData) { if (executionData == null) { throw new ArgumentNullException(nameof(executionData)); } ExecutionData = executionData; FilePrefix = new ScanFilePrefix(executionData.SessionId, executionData.Credential.UserName, ScanType); ScanLog = new DigitalSendJobInputLog(executionData, FilePrefix, ScanType); WorkflowLogger = new DeviceWorkflowLogger(executionData); }
/// <summary> /// Initializes a new instance of the <see cref="DigitalSendJobInputLog" /> class. /// </summary> /// <param name="executionData">The execution data.</param> /// <param name="filePrefix">The scan file prefix.</param> /// <param name="scanType">The scan type.</param> /// <exception cref="ArgumentNullException"><paramref name="executionData" /> is null.</exception> public DigitalSendJobInputLog(PluginExecutionData executionData, ScanFilePrefix filePrefix, string scanType) : base(executionData) { FilePrefix = filePrefix.ToString(); ScanType = scanType; DeviceId = null; Sender = null; JobEndStatus = null; PageCount = 0; DestinationCount = 1; Ocr = null; }
protected LinkScanActivityManager(PluginExecutionData executionData, LockTimeoutData lockTimeoutData) { if (executionData == null) { throw new ArgumentNullException(nameof(executionData)); } ExecutionData = executionData; FilePrefix = new ScanFilePrefix(executionData.SessionId, executionData.Credential.UserName, LinkJobType); WorkflowLogger = new DeviceWorkflowLogger(executionData); ConnectorLog = new ConnectorJobInputLog(executionData, LinkJobType); _lockTimeoutData = lockTimeoutData; }
private static void SaveToFolder(string folderDetails, string sessionId, string userName) { try { ScanFilePrefix filePrefix = new ScanFilePrefix(sessionId, userName, ScanType); //Maxmium retry is set to 500 in order to ensure scan is completed in case of a large document. Retry.WhileThrowing(() => _hpscanConfiguration.Button1000Button.IsEnabled(), 500, TimeSpan.FromSeconds(3), new List <Type>() { typeof(Exception) }); Thread.Sleep(ShortWaitWindowsTimeout); _hpscanConfiguration.Button1000Button.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); _saveOperations.DestinationButtButton.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); _saveOperations.FileTypeButton1Button.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); _saveOperations.ScanEdit1869Edit.PerformHumanAction(x => x.EnterText(filePrefix.ToString().ToLowerInvariant(), WindowsTimeout)); _saveOperations.OKButton1Button.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); _saveOperations.SendToEdit1159Edit.PerformHumanAction(x => x.EnterText(folderDetails, WindowsTimeout)); _saveOperations.DoNothingButtonRadioButton.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); //Checking for Incorrect Folder Path SaveToFolderPath saveToFolderPath = new SaveToFolderPath(_modelName); if (saveToFolderPath.OKButton1Button.IsEnabled(ShortTimeout)) { throw new Exception("Save To Folder Path is Incorrect"); } _saveOperations.ShowSaveAsdialoCheckBox.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); _hpscanConfiguration.Button1000Button.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); Retry.WhileThrowing(() => _hpscanConfiguration.SaveButton1006Button.IsEnabled(), 10, TimeSpan.FromSeconds(3), new List <Type>() { typeof(Exception) }); Thread.Sleep(ShortWaitWindowsTimeout); _hpscanConfiguration.SaveButton1006Button.PerformHumanAction(x => x.Click(WindowsTimeout)); if (_saveOperations.YesButton1ButtonReplace.IsAvailable()) { _saveOperations.YesButton1ButtonReplace.PerformHumanAction(x => x.ClickWithMouse(MouseButton.Left, WindowsTimeout)); } ExitTwain(); } catch (Exception ex) { throw new DeviceWorkflowException(ex.Message); } }
private string GetFileName(IDataRecord record) { string fileName = record["DeliveredFileName"] as string; // In some cases, we may need to use the email subject instead of the file name if (!string.IsNullOrEmpty(fileName) && !ScanFilePrefix.MatchesPattern(fileName)) { string emailSubject = record["EmailSubject"] as string; if (!string.IsNullOrEmpty(emailSubject)) { return(emailSubject + Path.GetExtension(fileName)); } } return(fileName); }
/// <summary> /// Applies the retention policy from the specified <see cref="OutputMonitorConfig"/> to the file. /// </summary> /// <param name="options">The validation/retention options.</param> /// <param name="isFileValid">if set to <c>true</c> the file should be considered valid.</param> public void ApplyRetention(OutputMonitorConfig options, bool isFileValid = true) { if (options == null) { throw new ArgumentNullException("options"); } // If the retention option is DoNothing, quit now if (options.Retention == RetentionOption.DoNothing) { return; } // Determine the "real" name for the file string file = _analyzer.File.FullName; string filePrefix = options.RetentionFileName ?? Path.GetFileNameWithoutExtension(file); // Determine whether we should retain or delete the output file(s) bool retain = options.Retention == RetentionOption.AlwaysRetain || (options.Retention == RetentionOption.RetainIfCorrupt && isFileValid == false); // Apply the retention option for the file string retentionDirectory = string.Empty; if (retain) { string session = ScanFilePrefix.Parse(filePrefix).SessionId; retentionDirectory = options.RetentionLocation.Replace("{SESSION}", session); System.IO.Directory.CreateDirectory(retentionDirectory); CopyFile(file, retentionDirectory, filePrefix, Path.GetExtension(file)); } File.Delete(file); // If we were expecting a metadata file, apply the retention options there as well if (options.LookForMetadataFile) { string metadataFile = Path.ChangeExtension(file, options.MetadataFileExtension); if (Retry.UntilTrue(() => File.Exists(metadataFile), 5, TimeSpan.FromSeconds(1))) { if (retain) { CopyFile(metadataFile, retentionDirectory, filePrefix, options.MetadataFileExtension); } File.Delete(metadataFile); } } }
/// <summary> /// Processes the located file. /// </summary> /// <param name="filePath">The file path.</param> /// <param name="createdEventTime">The created event time.</param> protected virtual void ProcessFile(string filePath, DateTime?createdEventTime = null) { TraceFactory.Logger.Debug("Found file: {0}".FormatWith(filePath)); try { string fileName = Path.GetFileName(filePath); ScanFilePrefix filePrefix = ScanFilePrefix.Parse(fileName); // Create the log for this file DigitalSendJobOutputLogger log = new DigitalSendJobOutputLogger(fileName, filePrefix.ToString(), filePrefix.SessionId); log.FileSentDateTime = System.IO.Directory.GetCreationTime(filePath); log.FileReceivedDateTime = createdEventTime; log.FileLocation = "{0} - {1}".FormatWith(Environment.MachineName, Path.GetDirectoryName(filePath)); // Validate and analyze the file OutputProcessor processor = new OutputProcessor(filePath); ValidationResult result = null; Retry.WhileThrowing( () => result = processor.Validate(Configuration), 10, TimeSpan.FromSeconds(2), new Collection <Type>() { typeof(IOException) }); DocumentProperties properties = processor.GetProperties(); log.FileSizeBytes = properties.FileSize; log.PageCount = properties.Pages; log.SetErrorMessage(result); // Clean up the file processor.ApplyRetention(Configuration, result.Succeeded); // Send the output log new DataLogger(GetLogServiceHost(filePrefix.SessionId)).Submit(log); } catch (IOException ex) { LogProcessFileError(filePath, ex); } catch (FormatException ex) { LogProcessFileError(filePath, ex); } }
/// <summary> /// Performs ScanToJobStorage job on Control Panel /// </summary> /// <param name="device"></param> /// <param name="jobStorageScanData"></param> /// <returns></returns> private PluginExecutionResult ExecuteJobStorageActivity(IDevice device, ScanActivityData jobStorageScanData, IAuthenticator authenticator) { var result = new PluginExecutionResult(PluginResult.Failed); // Make sure the device is in a good state UpdateStatus($"Setting up device at address {device.Address} for user {ExecutionData.Credential.UserName}"); var devicePrepManager = DevicePreparationManagerFactory.Create(device); devicePrepManager.WorkflowLogger = WorkflowLogger; devicePrepManager.InitializeDevice(true); // Load the Job storage application IJobStorageScanApp contentionJobStorageApp = ScanJobStorageAppFactory.Create(device); //Launch the Scan To Job Storage application UpdateStatus("ScanToJobStorage Activity: Launching the Scan To Job Storage application..."); contentionJobStorageApp.Launch(authenticator, AuthenticationMode.Lazy); //Enter the job name ScanFilePrefix FilePrefix = new ScanFilePrefix(ExecutionData.SessionId, ExecutionData.Credential.UserName, "Job Storage"); FilePrefix.MaxLength = 16; UpdateStatus("ScanToJobStorage Activity: Entering job name..."); contentionJobStorageApp.AddJobName(FilePrefix.ToString().ToLowerInvariant()); // Set job build contentionJobStorageApp.Options.SetJobBuildState((jobStorageScanData.PageCount > 1) ? true : false); try { ScanExecutionOptions options = new ScanExecutionOptions(); options.ValidateJobExecution = false; if (jobStorageScanData.PageCount > 1) { options.JobBuildSegments = jobStorageScanData.PageCount; } //Finish the job UpdateStatus("ScanToJobStorage Activity: Finishing the activity..."); if (contentionJobStorageApp.ExecuteScanJob(options)) { result = new PluginExecutionResult(PluginResult.Passed); } // Clean up try { devicePrepManager.NavigateHome(); if (devicePrepManager.SignOutRequired()) { UpdateStatus("ScanToJobStorage Activity: Signing Out..."); devicePrepManager.SignOut(); } UpdateStatus("ScanToJobStorage Activity: Activity finished"); } catch (Exception ex) when(ex is DeviceCommunicationException || ex is DeviceInvalidOperationException) { // Don't fail the activity if there is an exception here. ExecutionServices.SystemTrace.LogWarn($"Device could not return to home screen: {ex.ToString()}"); } } finally { // End of ScanToJobStorage activity ExecutionServices.SystemTrace.LogDebug("ScanToJobStorage activity completed"); } return(result); }
protected virtual bool ProcessMessage(EmailMessage message) { EmailAttachment attachment = message.Attachments.FirstOrDefault(); if (attachment != null) { // Determine if we need to pull the file name from the subject string fileName = attachment.FileName; if (!ScanFilePrefix.MatchesPattern(attachment.FileName)) { fileName = message.Subject + Path.GetExtension(attachment.FileName); } TraceFactory.Logger.Debug("Found attachment: " + fileName); try { ScanFilePrefix filePrefix = ScanFilePrefix.Parse(Path.GetFileName(fileName)); // Create the log for this file DigitalSendJobOutputLogger log = new DigitalSendJobOutputLogger(fileName, filePrefix.ToString(), filePrefix.SessionId); log.FileSentDateTime = message.DateTimeSent; log.FileReceivedDateTime = message.DateTimeReceived; log.FileLocation = _emailAddress.ToString(); // Save the attachment locally FileInfo file = attachment.Save(_tempPath, fileName); // Validate and analyze the file OutputProcessor processor = new OutputProcessor(file.FullName); ValidationResult result = null; Retry.WhileThrowing( () => result = processor.Validate(base.Configuration), 10, TimeSpan.FromSeconds(2), new Collection <Type>() { typeof(IOException) }); DocumentProperties properties = processor.GetProperties(); log.FileSizeBytes = properties.FileSize; log.PageCount = properties.Pages; log.SetErrorMessage(result); // Clean up the file processor.ApplyRetention(base.Configuration, result.Succeeded); // One last check - if there was more than one attachment, flag this as an error if (message.Attachments.Count > 1) { log.ErrorMessage += " {0} attachments with one email.".FormatWith(message.Attachments.Count); } // Send the output log new DataLogger(GetLogServiceHost(filePrefix.SessionId)).Submit(log); } catch (Exception ex) { LogProcessFileError(fileName, ex); return(false); } } else { TraceFactory.Logger.Debug("Found email with subject {0} but no attachments.".FormatWith(message.Subject)); } return(true); }
/// <summary> /// Performs ScanToEmail job on Control Panel /// </summary> /// <param name="device"></param> /// <param name="emailScanData"></param> /// <returns></returns> private PluginExecutionResult ExecuteEmailActivity(IDevice device, ScanActivityData emailScanData, IAuthenticator authenticator) { var result = new PluginExecutionResult(PluginResult.Failed); // Make sure the device is in a good state UpdateStatus($"Setting up device at address {device.Address} for user {ExecutionData.Credential.UserName}"); var devicePrepManager = DevicePreparationManagerFactory.Create(device); devicePrepManager.WorkflowLogger = WorkflowLogger; devicePrepManager.InitializeDevice(true); // Load the email application IEmailApp contentionEmailApp = EmailAppFactory.Create(device); //Launch the Scan to Email application UpdateStatus("ScanToEmail Activity: Launching the Scan To Email application..."); contentionEmailApp.Launch(authenticator, AuthenticationMode.Lazy); //Enter subject and file name ScanFilePrefix FilePrefix = new ScanFilePrefix(ExecutionData.SessionId, ExecutionData.Credential.UserName, "Email"); string fileName = FilePrefix.ToString().ToLowerInvariant(); contentionEmailApp.EnterSubject(fileName); UpdateStatus("ScanToEmail Activity: Email subject entered..."); contentionEmailApp.EnterFileName(fileName); UpdateStatus("ScanToEmail Activity: File name entered..."); List <string> emailList = new List <string>(); emailList.Add(emailScanData.EmailAddress); //Enter email address contentionEmailApp.EnterToAddress(emailList); UpdateStatus("ScanToEmail Activity: Email address entered..."); try { ScanExecutionOptions options = new ScanExecutionOptions(); options.ValidateJobExecution = false; if (emailScanData.PageCount > 1) { options.JobBuildSegments = emailScanData.PageCount; } //Finish the job UpdateStatus("ScanToEmail Activity: Finishing the activity..."); if (contentionEmailApp.ExecuteJob(options)) { result = new PluginExecutionResult(PluginResult.Passed); } // Clean up try { devicePrepManager.NavigateHome(); if (devicePrepManager.SignOutRequired()) { UpdateStatus("ScanToEmail Activity: Signing Out..."); devicePrepManager.SignOut(); } UpdateStatus("ScanToEmail Activity: Activity finished"); } catch (Exception ex) when(ex is DeviceCommunicationException || ex is DeviceInvalidOperationException) { // Don't fail the activity if there is an exception here. ExecutionServices.SystemTrace.LogWarn($"Device could not return to home screen: {ex.ToString()}"); } } finally { // End of ScanToEmail activity ExecutionServices.SystemTrace.LogDebug("ScanToEmail activity completed"); } return(result); }
/// <summary> /// Performs ScanToFolder job on Control Panel /// </summary> /// <param name="device"></param> /// <param name="folderScanData"></param> /// <returns></returns> private PluginExecutionResult ExecuteFolderActivity(IDevice device, ScanActivityData folderScanData, IAuthenticator authenticator) { var result = new PluginExecutionResult(PluginResult.Failed); // Make sure the device is in a good state UpdateStatus($"Setting up device at address {device.Address} for user {ExecutionData.Credential.UserName}"); var devicePrepManager = DevicePreparationManagerFactory.Create(device); devicePrepManager.WorkflowLogger = WorkflowLogger; devicePrepManager.InitializeDevice(true); // Load the network folder application INetworkFolderApp contentionFolderApp = NetworkFolderAppFactory.Create(device); //Launch the Scan to Network Folder app UpdateStatus("ScanToFolder Activity: Launching the Scan To Folder application..."); contentionFolderApp.Launch(authenticator, AuthenticationMode.Lazy); //Network credential being passed as parameter to access the folder and it is used by jediomninetworkfolderapp now UpdateStatus("ScanToFolder Activity: Entering folder path..."); contentionFolderApp.AddFolderPath(folderScanData.FolderPath, ExecutionData.Credential, true); // Enter the file name ScanFilePrefix FilePrefix = new ScanFilePrefix(ExecutionData.SessionId, ExecutionData.Credential.UserName, "Folder"); UpdateStatus("ScanToFolder Activity: Entering file name..."); contentionFolderApp.EnterFileName(FilePrefix.ToString().ToLowerInvariant()); // Set job build contentionFolderApp.Options.SetJobBuildState((folderScanData.PageCount > 1) ? true : false); try { ScanExecutionOptions options = new ScanExecutionOptions(); options.ValidateJobExecution = false; if (folderScanData.PageCount > 1) { options.JobBuildSegments = folderScanData.PageCount; } //Finish the job UpdateStatus("ScanToFolder Activity: Finishing the activity..."); if (contentionFolderApp.ExecuteJob(options)) { result = new PluginExecutionResult(PluginResult.Passed); } else { throw new DeviceWorkflowException(result.Message); } // Clean up try { devicePrepManager.NavigateHome(); if (devicePrepManager.SignOutRequired()) { UpdateStatus("ScanToFolder Activity: Signing Out..."); devicePrepManager.SignOut(); } UpdateStatus("ScanToFolder Activity: Activity finished"); } catch (Exception ex) when(ex is DeviceCommunicationException || ex is DeviceInvalidOperationException) { // Don't fail the activity if there is an exception here. ExecutionServices.SystemTrace.LogWarn($"Device could not return to home screen: {ex.ToString()}"); } } finally { // End of ScanToFolder activity ExecutionServices.SystemTrace.LogDebug("ScanToFolder activity completed"); } return(result); }
/// <summary> /// Processes the located file. /// </summary> /// <param name="filePath">The file path.</param> /// <param name="createdEventTime">The created event time.</param> protected override void ProcessFile(string filePath, DateTime?createdEventTime = null) { string fileName = Path.GetFileName(filePath); TraceFactory.Logger.Debug("Found file: {0}".FormatWith(fileName)); // Check to see if we have the associated HPF file - without it, we can't process this file string hpfFile = Path.ChangeExtension(filePath, ".hpf"); if (!Retry.UntilTrue(() => File.Exists(filePath), 30, TimeSpan.FromSeconds(2))) { TraceFactory.Logger.Debug("No associated HPF file - cannot process."); return; } // Extract the file prefix from the HPF metadata file ScanFilePrefix filePrefix = null; try { Retry.WhileThrowing( () => filePrefix = ExtractFileName(hpfFile), 10, TimeSpan.FromSeconds(2), new Collection <Type>() { typeof(IOException) }); } catch (IOException ex) { LogProcessFileError(fileName + " HPF file ", ex); return; } catch (FormatException ex) { LogProcessFileError(fileName + " HPF file ", ex); return; } try { // Create the log for this file DigitalSendJobOutputLogger log = new DigitalSendJobOutputLogger(filePrefix, Path.GetExtension(filePath)); log.FileName = Path.GetFileName(filePath); log.FileSentDateTime = System.IO.Directory.GetCreationTime(filePath); log.FileReceivedDateTime = createdEventTime; log.FileLocation = "{0} - {1}".FormatWith(Environment.MachineName, Path.GetDirectoryName(filePath)); // Validate and analyze the file OutputProcessor processor = new OutputProcessor(filePath); ValidationResult result = null; Retry.WhileThrowing( () => result = processor.Validate(Options), 10, TimeSpan.FromSeconds(2), new Collection <Type>() { typeof(IOException) }); DocumentProperties properties = processor.GetProperties(); log.FileSizeBytes = properties.FileSize; log.PageCount = properties.Pages; log.SetErrorMessage(result); // Clean up the file Options.RetentionFileName = filePrefix.ToString(); processor.ApplyRetention(Options, result.Succeeded); // Send the output log new DataLogger(GetLogServiceHost(filePrefix.SessionId)).Submit(log); } catch (IOException ex) { LogProcessFileError(fileName, ex); } catch (FormatException ex) { LogProcessFileError(fileName, ex); } // Create a notification file for the fax try { CreateNotificationFile(hpfFile, filePrefix); } catch (IOException ex) { TraceFactory.Logger.Error(ex); } }
/// <summary> /// Performs Fax job on Control Panel /// </summary> /// <param name="device"></param> /// <param name="controlPanelData"></param> /// <returns></returns> private PluginExecutionResult ExecuteFax(IDevice device, object controlPanelData, IAuthenticator authenticator) { var result = new PluginExecutionResult(PluginResult.Failed); FaxActivityData faxData = controlPanelData as FaxActivityData; // Make sure the device is in a good state UpdateStatus($"Setting up device at address {device.Address} for user {ExecutionData.Credential.UserName}"); var devicePrepManager = DevicePreparationManagerFactory.Create(device); devicePrepManager.WorkflowLogger = WorkflowLogger; devicePrepManager.InitializeDevice(true); // Load the fax application IFaxApp contentionFaxApp = FaxAppFactory.Create(device); //Launch the Fax application UpdateStatus("Fax Activity: Launching the Fax application..."); contentionFaxApp.Launch(authenticator, AuthenticationMode.Lazy); ScanFilePrefix FilePrefix = new ScanFilePrefix(ExecutionData.SessionId, ExecutionData.Credential.UserName, "Fax"); UpdateStatus("Fax Activity: Entering recipient fax number..."); if (string.IsNullOrEmpty(faxData.FaxNumber) || string.IsNullOrWhiteSpace(faxData.FaxNumber)) { // Apply settings from configuration contentionFaxApp.AddRecipient(FilePrefix.ToFaxCode()); } else { contentionFaxApp.AddRecipient(faxData.FaxNumber); } //Set job build contentionFaxApp.Options.SetJobBuildState((faxData.PageCount > 1) ? true : false); try { // Start the job ScanExecutionOptions options = new ScanExecutionOptions(); options.ValidateJobExecution = false; if (faxData.PageCount > 1) { options.JobBuildSegments = faxData.PageCount; } //Finish the job UpdateStatus("Fax Activity: Finishing the activity..."); if (contentionFaxApp.ExecuteJob(options)) { result = new PluginExecutionResult(PluginResult.Passed); } // Clean up try { devicePrepManager.NavigateHome(); if (devicePrepManager.SignOutRequired()) { UpdateStatus("Fax Activity: Signing Out..."); devicePrepManager.SignOut(); } } catch (Exception ex) when(ex is DeviceCommunicationException || ex is DeviceInvalidOperationException) { // Don't fail the activity if there is an exception here. ExecutionServices.SystemTrace.LogWarn($"Device could not return to home screen: {ex.ToString()}"); } } finally { // End of fax activity ExecutionServices.SystemTrace.LogDebug("Fax activity completed"); } return(result); }