private static bool ValidateFileExtension(string extension, IBinaryElementConstraints constraints) { return(Enum.TryParse(extension, true, out FileFormat format) && Enum.IsDefined(typeof(FileFormat), format) && format.ToString().Equals(extension, StringComparison.OrdinalIgnoreCase) && constraints.SupportedFileFormats.Any(f => f == format)); }
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private void VerifyBinaryConstraints(int templateCode, IBinaryElementConstraints binaryElementConstraints) { if (binaryElementConstraints.SupportedFileFormats == null) { throw new TemplateValidationException(templateCode, TemplateElementValidationError.MissingSupportedFileFormats); } if (!binaryElementConstraints.SupportedFileFormats.Any()) { throw new TemplateValidationException(templateCode, TemplateElementValidationError.EmptySupportedFileFormats); } if (binaryElementConstraints.MaxFilenameLength <= 0) { throw new TemplateValidationException(templateCode, TemplateElementValidationError.NegativeMaxFilenameLength); } if (binaryElementConstraints.MaxSize <= 0) { throw new TemplateValidationException(templateCode, TemplateElementValidationError.NegativeMaxSize); } if (binaryElementConstraints.MaxSize > _maxBinarySize) { throw new TemplateValidationException(templateCode, TemplateElementValidationError.MaxSizeLimitExceeded); } }
private static IImageInfo ValidateBitmapImageFormat(int templateCode, IBinaryElementConstraints constraints, FileFormat fileFormat, Stream inputStream) { var imageFormats = constraints.SupportedFileFormats .Aggregate( new List <string>(), (result, next) => { if (ImageFormatToMimeTypeMap.TryGetValue(next, out var imageFormat)) { result.Add(imageFormat); } return(result); }); inputStream.Position = 0; var format = Image.DetectFormat(inputStream); if (format == null) { throw new InvalidBinaryException(templateCode, new InvalidImageError()); } var extension = fileFormat.ToString().ToLowerInvariant(); if (!format.FileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { // Image format is not consistent with the filename extension throw new InvalidBinaryException(templateCode, new BinaryExtensionMismatchContentError(extension, format.Name.ToLowerInvariant())); } if (!imageFormats.Contains(format.DefaultMimeType, StringComparer.OrdinalIgnoreCase)) { throw new InvalidBinaryException(templateCode, new BinaryInvalidFormatError(format.Name.ToLowerInvariant())); } IImageInfo imageInfo; try { inputStream.Position = 0; imageInfo = Image.Identify(inputStream); } catch (Exception) { throw new InvalidBinaryException(templateCode, new InvalidImageError()); } return(imageInfo); }