/// <summary> /// Validates the file, using the <see cref="OutputMonitorConfig"/> provided. /// </summary> /// <param name="options">The validation options.</param> /// <returns></returns> public ValidationResult Validate(OutputMonitorConfig options) { if (options == null) { throw new ArgumentNullException("options"); } // Perform basic validation on the file FileValidationResult fileValidation = _analyzer.Validate(); ValidationResult result = new ValidationResult(fileValidation.Success, fileValidation.Message); if (!result.Succeeded) { return(result); } // If requested, ensure that there is an associated metadata file if (options.LookForMetadataFile) { string metadataFile = Path.ChangeExtension(_analyzer.File.FullName, options.MetadataFileExtension); if (!File.Exists(metadataFile)) { return(new ValidationResult(false, "Metadata file not found: {0}".FormatWith(Path.GetFileName(metadataFile)))); } } // If we reach this point, the file validated successfully return(new ValidationResult(true)); }
public ValidationResult IsValid(T parameter) { var errorMessages = new List <string>(); var filePath = parameter.ToString(); filePath = filePath.GetDefaultPath(DefaultDirectory, Extension); var validationResult = new FileValidationResult(filePath); if (string.IsNullOrEmpty(Path.GetFileName(validationResult.FilePath))) { errorMessages.Add("Invalid: File name can't be empty"); } else if (!Directory.Exists(Path.GetDirectoryName(validationResult.FilePath))) { errorMessages.Add("Invalid: Directory doesn't exist"); } else if (File.Exists(validationResult.FilePath)) { errorMessages.Add($"Invalid: File '{Path.GetFileName(validationResult.FilePath)}' under given Directory already exist"); } validationResult.ErrorMessages = errorMessages; return(validationResult); }
public async Task GenerateAsync(IReportServiceContext reportServiceContext, IEnumerable <ValidationErrorRow> validationErrorDtos, bool isSchemaError, CancellationToken cancellationToken) { var validationErrorDtosList = validationErrorDtos.ToList(); var errors = validationErrorDtosList.Where(x => x.Severity.CaseInsensitiveEquals("E") || x.Severity.CaseInsensitiveEquals("F")) .ToArray(); var warnings = validationErrorDtosList .Where(x => x.Severity.CaseInsensitiveEquals("W")).ToArray(); var ilrValidationResult = new FileValidationResult { TotalLearners = GetNumberOfLearners(reportServiceContext), TotalErrors = errors.Length, TotalWarnings = warnings.Length, TotalWarningLearners = warnings.DistinctByCount(x => x.LearnerReferenceNumber?.Trim()), TotalErrorLearners = errors.DistinctByCount(x => x.LearnerReferenceNumber?.Trim()), ErrorMessage = validationErrorDtosList .FirstOrDefault(x => x.Severity.CaseInsensitiveEquals("F")) ?.ErrorMessage, IsSchemaError = isSchemaError }; var fileName = _fileNameService.GetFilename(reportServiceContext, "Rule Violation Report", OutputTypes.Json); using (var fileStream = await _fileService.OpenWriteStreamAsync(fileName, reportServiceContext.Container, cancellationToken)) { _jsonSerializationService.Serialize(ilrValidationResult, fileStream); } }
/// <summary> /// Performs basic validation on the file being analyzed by this <see cref="FileAnalyzer" />. /// </summary> /// <returns>A <see cref="FileValidationResult" /> object representing the result of validation.</returns> public override FileValidationResult Validate() { try { using (ExcelApp app = new ExcelApp()) { app.Open(File); } return(FileValidationResult.Pass); } catch (COMException ex) { LogWarn("File failed to open: " + ex.Message); return(FileValidationResult.Fail(ex.Message)); } }
/// <summary> /// Performs basic validation on the file being analyzed by this <see cref="FileAnalyzer" />. /// </summary> /// <returns>A <see cref="FileValidationResult" /> object representing the result of validation.</returns> public override FileValidationResult Validate() { try { LogDebug($"Loading TIF image: {File.Name}"); using (Image tiff = Image.FromFile(File.FullName)) { return(FileValidationResult.Pass); } } catch (OutOfMemoryException) { LogWarn("Unable to load image."); return(FileValidationResult.Fail("The file is not a valid TIF document.")); } }
private void GenerateFrontEndValidationReport( IReportServiceContext reportServiceContext, List <ValidationErrorDto> validationErrorDtos) { var errors = validationErrorDtos.Where(x => string.Equals(x.Severity, "E", StringComparison.OrdinalIgnoreCase) || string.Equals(x.Severity, "F", StringComparison.OrdinalIgnoreCase)).ToArray(); var warnings = validationErrorDtos.Where(x => string.Equals(x.Severity, "W", StringComparison.OrdinalIgnoreCase)).ToArray(); _ilrValidationResult = new FileValidationResult { TotalLearners = GetNumberOfLearners(reportServiceContext), TotalErrors = errors.Length, TotalWarnings = warnings.Length, TotalWarningLearners = warnings.DistinctByCount(x => x.LearnerReferenceNumber), TotalErrorLearners = errors.DistinctByCount(x => x.LearnerReferenceNumber), ErrorMessage = validationErrorDtos.FirstOrDefault(x => string.Equals(x.Severity, "F", StringComparison.OrdinalIgnoreCase))?.ErrorMessage, TotalDataMatchErrors = _validationStageOutputCache.DataMatchProblemCount, TotalDataMatchLearners = _validationStageOutputCache.DataMatchProblemLearnersCount }; }
/// <summary> /// Performs basic validation on the file being analyzed by this <see cref="FileAnalyzer" />. /// </summary> /// <returns>A <see cref="FileValidationResult" /> object representing the result of validation.</returns> public override FileValidationResult Validate() { string firstLine = System.IO.File.ReadLines(File.FullName).FirstOrDefault(); // If the first line is empty, the file is invalid. if (string.IsNullOrEmpty(firstLine)) { return(FileValidationResult.Fail("Empty file.")); } // A well-formed PDF must start with this text. if (!firstLine.StartsWith("%PDF-", StringComparison.OrdinalIgnoreCase)) { return(FileValidationResult.Fail("Malformed first line.")); } // There should be an EOF flag at the end. string lastLine = System.IO.File.ReadLines(File.FullName).Last(); if (lastLine != "%%EOF") { return(FileValidationResult.Fail("File did not include EOF flag.")); } // Finally, use the PDF library to load the file and ensure there were no other problems. try { LogDebug($"Loading PDF file: {File.Name}"); using (PdfDocument doc = PdfReader.Open(File.FullName, PdfDocumentOpenMode.ReadOnly)) { return(FileValidationResult.Pass); } } catch (Exception ex) when(ex is PdfSharpException || ex is InvalidOperationException) { LogWarn("File failed to open: " + ex.Message); return(FileValidationResult.Fail(ex.Message)); } }
/// <summary>Validates an uploaded file for size and extension</summary> /// <param name="file">File to be validated</param> /// <returns> /// <see cref="FileValidationResult" /> /// </returns> public static FileValidationResult Validate(this HttpPostedFileBase file) { int maxSize = WebConfig.Get("max_upload_size", 4194304); // default is 4MB string acceptedFiles = WebConfig.Get("accepted_file_types", ".pdf,.jpg,.png,.doc,.docx"); var validFileTypes = acceptedFiles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); FileValidationResult result = new FileValidationResult(); result.IsValid = false; if (file.IsMissing()) { result.Message = "file is missing"; return(result); } if (file.ContentLength < 1) { result.Message = "empty file"; return(result); } if (file.ContentLength > maxSize) { result.Message = "file is too large"; return(result); } if (!HtmlValidator.CheckFileType(file.FileName, validFileTypes)) { if (file.ContentLength > maxSize) { result.Message = "Invalid file type"; return(result); } } result.Message = "file is valid"; result.IsValid = true; return(result); }
private void btnProcess_Click(object sender, EventArgs e) { if (MP.isProcessing) { this.cancelSource.Cancel(); return; } if (MP.GetNumFiles() == 0) { MessageBox.Show("No files selected.", "No files selected", MessageBoxButtons.OK); return; } int resizeValue = 0; bool success = MediaProcessorOptions.TryParseResizeValue(this.txtResize.Text, (comboOptions)this.cbxResizeType.SelectedIndex, out resizeValue); if (!success) { MessageBox.Show("Invalid value entered for resizing images to.", "Invalid entry", MessageBoxButtons.OK); return; } int videoResizeValue = 0; success = MediaProcessorOptions.TryParseResizeValue(this.txtVideoResize.Text, (comboOptions)this.cbxVideoResizeType.SelectedIndex, out videoResizeValue); if (!success) { MessageBox.Show("Invalid value entered for resizing videos to.", "Invalid entry", MessageBoxButtons.OK); return; } success = this.TryReadDefaultCropRatio(out float?defaultCropRatio); if (!success) { MessageBox.Show("Invalid value entered for crop ratio.", "Invalid entry", MessageBoxButtons.OK); return; } MediaProcessorOptions options = new MediaProcessorOptions( (comboOptions)this.cbxResizeType.SelectedIndex, (comboOptions)this.cbxVideoResizeType.SelectedIndex, (outTypeOptions)this.cbxOutputType.SelectedIndex, (videoOutTypeOptions)this.cbxVideoOutputType.SelectedIndex, resizeValue, videoResizeValue, (int)nudQuality.Value, (int)nudVideoQuality.Value, defaultCropRatio ); MP.SetOptions(options); MP.SetFileSuffix(txtSuffix.Text); FileValidationResult val = MP.ValidateFileList(); if (val.noInputList.Count > 0 || val.folderFailedList.Count > 0) { MessageBox.Show(val.message, "Invalid file list", MessageBoxButtons.OK); return; } if (val.outputExistsList.Count > 0) { DialogResult res = MessageBox.Show("Overwrite these files?\r\n\r\n" + val.message, "Files already exist", MessageBoxButtons.YesNo); if (res == DialogResult.No) { return; } } CancellationToken token = this.cancelSource.Token; this.OnProcessingStart(); Task processingTask = Task.Factory.StartNew(() => { MP.Run(token, UpdateOnProgress); if (token.IsCancellationRequested) { this.OnProcessingCancelled(); } else { this.OnProcessingComplete(MP.GetResult()); } }, token); }