/// <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 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); } }
/// <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; }
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); } }
/// <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> /// 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); }
/// <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> /// 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); }
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); } }
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); }