コード例 #1
0
        private bool AllowExtension()
        {
            string fileExtension = System.IO.Path.GetExtension(this.FileName).ToLower();

            string[] extensions = AllowedExtensions.Split(' ');
            foreach (string extension in extensions)
            {
                if (extension.Equals(fileExtension))
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #2
0
    /// <summary>
    /// Determines whether file with specified extension can be uploaded.
    /// </summary>
    /// <param name="extension">File extension to check</param>
    protected bool IsExtensionAllowed(string extension)
    {
        if (string.IsNullOrEmpty(AllowedExtensions))
        {
            return(true);
        }


        // Remove starting dot from tested extension
        extension = extension.TrimStart('.').ToLowerCSafe();

        string extensions = ";" + AllowedExtensions.ToLowerCSafe() + ";";

        return((extensions.Contains(";" + extension + ";")) || (extensions.Contains(";." + extension + ";")));
    }
コード例 #3
0
        private IReadOnlyCollection <FilePath> FilterOutSearchedPaths(IEnumerable <FilePath> filePaths)
        {
            if (AllowedExtensions != null)
            {
                filePaths = filePaths.Where(path => AllowedExtensions.Contains(path.GetExtension()));
            }

            var includedPatternsString = RequiredPatterns != null?string.Join(';', RequiredPatterns) : "*";

            var excludedPatternsString = ExcludedPatterns != null?string.Join(';', ExcludedPatterns) : null;

            filePaths = FilesystemPathsMatcher.MatchSearchResult(includedPatternsString, excludedPatternsString, filePaths);

            return(filePaths.ToList());
        }
コード例 #4
0
        public virtual int _GetUniqueIdentifier()
        {
            var hashCode = 399326290;

            hashCode = hashCode * -1521134295 + (Id?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (FileName?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (FolderPath?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (MaxFileSize?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (AllowedExtensions?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (Blob?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (StorageMedium?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (UploadedBy?.GetHashCode() ?? 0);
            hashCode = hashCode * -1521134295 + (UploadDateTime?.GetHashCode() ?? 0);
            return(hashCode);
        }
コード例 #5
0
        /// <summary>
        /// Method to retrieve mime type from extension
        /// </summary>
        public static string GetTypeFromExtension(string extension)
        {
            if (extension == null)
            {
                throw new ArgumentNullException(nameof(extension));
            }

            if (!extension.StartsWith("."))
            {
                extension = "." + extension;
            }

            string mime;

            return(AllowedExtensions.TryGetValue(extension, out mime) ? mime : "application/octet-stream");
        }
コード例 #6
0
 public FileSelector(string RelativeDirectoryPath, string RelativeFilePath, params string[] AllowedExtensions)
 {
     CurrentFilepath            = string.Copy(RelativeFilePath);
     DisplayedfileNames         = new List <string>();
     this.RelativeDirectoryPath = RelativeDirectoryPath;
     this.RelativeFilePath      = RelativeFilePath;
     if (AllowedExtensions.Length == 0)
     {
         this.AllowedExtensions = null;
     }
     else
     {
         this.AllowedExtensions = AllowedExtensions.ToList();
     }
     InitializeComponent();
 }
コード例 #7
0
        public async Task CreateFile(FileContent file)
        {
            var path             = new CloudPath(file.Path, file.Filename);
            var fileAbsolutePath = GetAbsolutePath(path.TargetPath);

            var extension = Path.GetExtension(file.Filename);

            if (!AllowedExtensions.Contains(extension) && !file.ContentType.Contains("image"))
            {
                throw new StorageException("Invalid file(s). Note that allowed type files are all image types, video type mp4, webm, ogg, audio types mp3, ogg, wav, pdf, xlsx, xls, docx, ppt, pptx, zip, xml, html, css, js, json, woff and dicos files.");
            }

            var newFilePath = GetNewFilePathIfExists(fileAbsolutePath, fileAbsolutePath);
            await Task.Run(() =>
            {
                System.IO.File.WriteAllBytes(newFilePath, file.FileBytes);
            });
        }
コード例 #8
0
        internal bool DoDraggedFilesHaveAllowedExtensions(string[] fileNames)
        {
            if (AllowedExtensions.ToLower().Contains("*"))
            {
                return(true);
            }

            foreach (string filename in fileNames)
            {
                // If at leats one of the current dragged files extension is not found in the allowed extensions array, we return false
                if (AllowedExtensions.ToLower().Contains(System.IO.Path.GetExtension(filename).ToLower()) == false)
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #9
0
        /// <summary>
        /// Check if object is valid
        /// </summary>
        /// <param name="value">object</param>
        /// <returns>return true if object is valid</returns>
        public override bool IsValid(object value)
        {
            var file = value as IFormFile;

            if (file == null && !NullPossible)
            {
                return(false);
            }

            if (file == null && NullPossible)
            {
                return(true);
            }

            var fileName = file.FileName;

            return(AllowedExtensions.Any(exten => fileName.EndsWith(exten)));
        }
コード例 #10
0
    public static SqlString ExtractDomain(SqlString absoluteUri)
    {
        if (!ExtractIPAddress(absoluteUri).IsNull)
        {
            return(ExtractIPAddress(absoluteUri));
        }
        else
        {
            SqlString host = ExtractHost(absoluteUri);

            if (host.IsNull)
            {
                return("UNKNOWN");
            }
            else
            {
                string[] split = host.Value.Split('.');

                //HACK: Concession for http://localhost and http://sub.localhost ...
                if (split[split.Length - 1].ToLowerInvariant() == "localhost")
                {
                    return(new SqlString(split[split.Length - 1]));
                }

                if (split.Length < 3)
                {
                    return(host);
                }
                else
                {
                    if (AllowedExtensions.ContainsKey(split[split.Length - 2] + '.' + split[split.Length - 1]) || split[split.Length - 2].Length == 2)
                    {
                        return(new SqlString(split[split.Length - 3] + '.' + split[split.Length - 2] + '.' + split[split.Length - 1]));
                    }
                    else
                    {
                        return(new SqlString(split[split.Length - 2] + '.' + split[split.Length - 1]));
                    }
                }
            }
        }
    }
コード例 #11
0
        protected override void OnInit(EventArgs e)
        {
            // check the required attributes have been defined (AllowedExtensions, FormFieldName)
            if (String.IsNullOrEmpty(AllowedExtensions))
            {
                throw new Exception("AllowedExtensions is a required attribute for the FileUploadField component.");
            }
            if (String.IsNullOrEmpty(FormFieldName))
            {
                throw new Exception("FormFieldName is a required attribute for the FileUploadField component.");
            }

            // Note: should always validate that FormFieldName is a valid string, so just don't be silly with it

            // ensure that all extensions are wrapped in single quote for the JS array
            if (!String.IsNullOrEmpty(AllowedExtensions))
            {
                AllowedExtensionsJsArray = "'" + AllowedExtensions.Replace(",", "','") + "'";
            }
        }
コード例 #12
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            List <HttpPostedFileBase> _files = new List <HttpPostedFileBase>();

            if (HasMultiple)
            {
                _files.AddRange(value as List <HttpPostedFileBase>);
            }
            else
            {
                _files.Add(value as HttpPostedFileBase);
            }

            foreach (HttpPostedFileBase _file in _files)
            {
                if (_file != null)
                {
                    if (AllowedExtensions.Contains(Path.GetExtension(_file.FileName.ToLower())))
                    {
                        if (MaxFileSize >= ((_file.InputStream.Length / 1024f) / 1024f))
                        {
                            return(null);
                        }
                        else
                        {
                            return(new ValidationResult(string.Format("Invalid file. File should be less than {0} Mb", MaxFileSize)));
                        }
                    }
                    else
                    {
                        return(new ValidationResult(string.Format("Invalid file. Only {0} are supported", string.Join(", ", AllowedExtensions))));
                    }
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
コード例 #13
0
        protected override int Process()
        {
            foreach (var file in Files ?? Enumerable.Empty <string> ())
            {
                var result = 0;

                try {
                    var allowProcessFile = true;

                    if (AllowedExtensions.Count > 0)
                    {
                        var ext = Path.GetExtension(file).ToLowerInvariant();
                        allowProcessFile = null != AllowedExtensions.FirstOrDefault(e => e == ext);
                    }

                    if (!File.Exists(file))
                    {
                        throw new FileNotFoundException("File not found.", file);
                    }

                    if (allowProcessFile)
                    {
                        PreProcessFile(file);
                        result = ProcessFile(file);
                        PostProcessFile(file);
                    }
                }
                catch (Exception ex) {
                    ProcessFileCatch(ex);
                    result = 1;
                }

                if (result != 0 && !ContinueOnErrors)
                {
                    return(1);
                }
            }

            return(0);
        }
コード例 #14
0
        /// <summary>
        /// 检查是否合法
        /// 等于null时会通过
        /// 如果文件必填请使用Required属性
        /// </summary>
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return(true);
            }
            var file              = (IHttpPostedFile)value;
            var extension         = Path.GetExtension(file.FileName).ToLower();
            var allowedExtensions = AllowedExtensions.Split(',');

            if (!allowedExtensions.Contains(extension))
            {
                throw new BadRequestException("File extension is not allowed");
            }
            if (file.Length > MaximumSize)
            {
                var msg = new T(
                    "File is too big, the maximum size allowed is {0}",
                    FileUtils.GetSizeDisplayName(MaximumSize));
                throw new BadRequestException(msg);
            }
            return(true);
        }
コード例 #15
0
        public override bool IsValid(object value)
        {
            if (value == null || !(value is HttpPostedFileBase))
            {
                return(true);
            }

            string[] allowedExtensions = AllowedExtensions.ToLower(CultureInfo.InvariantCulture).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var      img = (HttpPostedFileBase)value;
            var      ext = Path.GetExtension(img.FileName);

            if (!img.ContentType.StartsWith("image/") || !allowedExtensions.Contains(ext.ToLower(CultureInfo.InvariantCulture)))
            {
                ErrorMessage = "Accepted File Types: " + AllowedExtensions;
                return(false);
            }
            else if (img.ContentLength > MaxFileSizeMb * 1024 * 1024)
            {
                ErrorMessage = $"Maximum Upload Size: {MaxFileSizeMb}MB";
                return(false);
            }
            return(true);
        }
コード例 #16
0
        public override bool IsValid(object value)
        {
            HttpPostedFileBase file = value as HttpPostedFileBase;
            bool isValid            = true;

            if (file != null)
            {
                var fileName = file.FileName;
                isValid = AllowedExtensions.Any(y => fileName.EndsWith(y));

                if (isValid == false)
                {
                    ErrorMessage = string.Format("Only {0} files ext are allowed.", string.Join(", ", AllowedExtensions));
                }
                //Check Size
                if (file.ContentLength > AllowedContentLength)
                {
                    isValid      = false;
                    ErrorMessage = "File too large, maximum allowed upto " + (AllowedContentLength / 2048).ToString() + "Mb.";
                }
            }

            return(isValid);
        }
コード例 #17
0
        protected override void ValidateAsActualType(FileInfo value, string parameterValue)
        {
            if (ShouldExist && !value.Exists)
            {
                ValidationFailed(FileMissingMessage, parameterValue);
            }

            if (AllowedExtensions != null && AllowedExtensions.Count > 0)
            {
                string extension = value.Extension;
                if (!AllowedExtensions.Any(ext => $".{ext}".Equals(extension, StringComparison.OrdinalIgnoreCase)))
                {
                    StringBuilder allowedExtensions = AllowedExtensions.Aggregate(new StringBuilder(), (sb, ext) =>
                    {
                        if (sb.Length > 0)
                        {
                            sb.Append(", ");
                        }
                        return(sb.Append(ext));
                    });
                    ValidationFailed(InvalidExtensionMessage, parameterValue, allowedExtensions);
                }
            }
        }
コード例 #18
0
        protected override Icon GetItem(FileInfo file)
        {
            if (file.Extension.Equals(".css", StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            //first, see if we've already got this sprite definition
            if (_sprites.Any(x => x.Key == file))
            {
                return(null);
            }

            //see if there is an associated .CSS file for this current file

            //ensures we only resolve the files once
            if (_resolvedFiles == null)
            {
                _resolvedFiles = AllowedExtensions.SelectMany(x => RootFolder.GetFiles(x, SearchOption.AllDirectories)).ToArray();
            }

            var spriteDefinition = _resolvedFiles
                                   .Where(x => x.Name.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase))
                                   .Where(x => Path.GetExtension(file.Name) != Path.GetExtension(x.Name))
                                   .Where(x => Path.GetFileNameWithoutExtension(file.Name) == Path.GetFileNameWithoutExtension(x.Name))
                                   .SingleOrDefault();

            if (spriteDefinition != null)
            {
                _sprites.Add(new KeyValuePair <FileInfo, FileInfo>(file, spriteDefinition));
                //since it's a Sprite, don't include it in the results
                return(null);
            }

            return(base.GetItem(file));
        }
コード例 #19
0
        /// <summary>
        /// This method give access to a file that was uploaded.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task UploadFile(IBrowserFile file)
        {
            // locals
            UploadedFileInfo uploadedFileInfo = null;
            bool             abort            = false;

            // locals
            MemoryStream ms = null;

            // verify the file exists
            if (file != null)
            {
                try
                {
                    // the partialGuid is need to ensure uniqueness
                    string partialGuid = Guid.NewGuid().ToString().Substring(0, PartialGuidLength);

                    // create the uploadedFileInfo
                    uploadedFileInfo = new UploadedFileInfo(file, partialGuid, AppendPartialGuid, UploadFolder);

                    // if the file is too large
                    if ((MaxFileSize > 0) && (file.Size > MaxFileSize))
                    {
                        // Show the FileTooLargeMessage
                        status = FileTooLargeMessage;

                        // Upload was aborted
                        uploadedFileInfo.Aborted      = true;
                        uploadedFileInfo.ErrorMessage = FileTooLargeMessage;
                        uploadedFileInfo.Exception    = new Exception("The file uploaded was too large.");
                    }
                    else
                    {
                        // Create a new instance of a 'FileInfo' object.
                        FileInfo fileInfo = new(file.Name);

                        // Set the extension. The ToLower is for just in case. I don't know if it's even possible for an extension to be upper case
                        uploadedFileInfo.Extension = fileInfo.Extension.ToLower();

                        // if FilterByExtension is true and the AllowedExtensions text exists
                        if ((FilterByExtension) && (!String.IsNullOrWhiteSpace(AllowedExtensions)))
                        {
                            // verify the extension exists
                            if (!String.IsNullOrWhiteSpace(fileInfo.Extension))
                            {
                                // If the allowed extensions // fixed issue where uploading
                                abort = !AllowedExtensions.ToLower().Contains(fileInfo.Extension.ToLower());
                            }
                            else
                            {
                                // you must have an extension
                                abort = true;
                            }
                        }

                        // Set aborted to true
                        uploadedFileInfo.Aborted = abort;

                        // if we should continue
                        if (!abort)
                        {
                            // create the memoryStream
                            ms = new MemoryStream();

                            using var stream = file.OpenReadStream(MaxFileSize);
                            byte[] buffer = new byte[4 * 1096];
                            int    bytesRead;
                            double totalRead = 0;

                            progressVisible = true;

                            while ((bytesRead = await stream.ReadAsync(buffer)) != 0)
                            {
                                totalRead += bytesRead;
                                await ms.WriteAsync(buffer);

                                progressPercent = (int)((totalRead / file.Size) * 100);
                                StateHasChanged();
                            }

                            progressVisible = false;

                            //// await for the data to be copied to the memory stream
                            //await file.OpenReadStream(MaxFileSize).CopyToAsync(ms);

                            // Check for abort 1 more time
                            uploadedFileInfo = CheckSize(fileInfo.Extension, ms, uploadedFileInfo);

                            // if abort
                            if (uploadedFileInfo.Aborted)
                            {
                                // Do not process due to size is not valid, message has already been set
                                abort = true;
                            }
                        }

                        // if we should continue
                        if (!abort)
                        {
                            // if the value for SaveToDisk is true
                            if (SaveToDisk)
                            {
                                // set the full path
                                string path = Path.Combine(UploadFolder, uploadedFileInfo.FullName);

                                // save the file using the FullName (If AppendPartialGuid is still true, than the Name.PartialGuid is the FullName
                                using FileStream fileStream = new(path, FileMode.Create, FileAccess.Write);
                                // write out the file
                                ms.WriteTo(fileStream);
                            }
                            else
                            {
                                // Set the MemoryStream, to allow people to save outside of the project
                                // folder, to disk or other processing like virus scans.
                                uploadedFileInfo.Stream = ms;
                            }

                            // if there is a CustomSave
                            if (!String.IsNullOrWhiteSpace(CustomSuccessMessage))
                            {
                                // Show the CustomSuccessMessage
                                status = CustomSuccessMessage;
                            }
                            else
                            {
                                // set the status
                                status = $"Saved file {file.Size} bytes from {file.Name}";
                            }

                            // Set additional properties for UploadFileInfo from this component; these values may be null.
                            uploadedFileInfo.CustomId = CustomId;
                            uploadedFileInfo.Tag      = Tag;

                            // The upload has completed
                            //UploadComplete = true;
                        }
                        else
                        {
                            // If a CustomExtensionMessage has been set
                            if (!string.IsNullOrWhiteSpace(CustomExtensionMessage))
                            {
                                // Display the Custom extension doesn't validate message
                                uploadedFileInfo.ErrorMessage = CustomExtensionMessage;
                            }
                            else
                            {
                                // Can't think of a better message than this yet, just woke up
                                uploadedFileInfo.ErrorMessage = "The file uploaded is an invalid extension.";
                            }

                            // Show the exception
                            uploadedFileInfo.Exception = new Exception(uploadedFileInfo.ErrorMessage);
                        }
                    }
                }
                catch (Exception error)
                {
                    // Upload was aborted
                    uploadedFileInfo.Aborted = true;

                    // Store the Exception
                    uploadedFileInfo.Exception = error;

                    // if a CustomErrorMessage is set
                    if (!String.IsNullOrWhiteSpace(CustomErrorMessage))
                    {
                        // Show the custom error message
                        status = CustomErrorMessage;
                    }
                    else
                    {
                        // show the full error
                        status = error.ToString();
                    }

                    // set the error message
                    uploadedFileInfo.ErrorMessage = status;
                }
                finally
                {
                    // Notify the caller the upload was successful or aborted due to an error
                    FileUploaded(uploadedFileInfo);
                }
            }
        }
コード例 #20
0
 public PdfCompressScannedScript(string [] args) : base(args)
 {
     AllowedExtensions.Add(".pdf");
     ContinueOnErrors = true;
 }
コード例 #21
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value is HttpPostedFileBase)
            {
                HttpPostedFileBase file          = (HttpPostedFileBase)value;
                string             fileName      = file.FileName;
                string             fileExtension = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
                int fileSize = file.ContentLength;

                if (AllowedExtensions.Contains(fileExtension))
                {
                    if (fileSize <= ContentLength)
                    {
                        return(ValidationResult.Success);
                    }
                    else
                    {
                        return(new ValidationResult("The Uploaded file must be less than or equal" + ContentLength / 1024 / 1024 + "MB."));
                    }
                }
                else
                {
                    return(new ValidationResult("The Uploaded file must be of one these extensions (" + AllowedExtensions.ToString() + ")."));
                }
            }
            else
            {
                return(new ValidationResult("You Should Upload File."));
            }
        }
コード例 #22
0
 public PdfCombineScript(string [] args) : base(args)
 {
     AllowedExtensions.Add(".pdf");
     ContinueOnErrors = false;
 }
コード例 #23
0
 public string ToPrettyString()
 {
     return("Assignment {" +
            ($"\n{nameof(Id)}: {Id}," +
             $"\n{nameof(Name)}: {Name}," +
             $"\n{nameof(Description)}: {Description}," +
             $"\n{nameof(CreatedAt)}: {CreatedAt}," +
             $"\n{nameof(UpdatedAt)}: {UpdatedAt}," +
             $"\n{nameof(DueAt)}: {DueAt}," +
             $"\n{nameof(LockAt)}: {LockAt}," +
             $"\n{nameof(UnlockAt)}: {UnlockAt}," +
             $"\n{nameof(HasOverrides)}: {HasOverrides}," +
             $"\n{nameof(AllDates)}: {AllDates?.ToPrettyString()}," +
             $"\n{nameof(CourseId)}: {CourseId}," +
             $"\n{nameof(HtmlUrl)}: {HtmlUrl}," +
             $"\n{nameof(SubmissionsDownloadUrl)}: {SubmissionsDownloadUrl}," +
             $"\n{nameof(AssignmentGroupId)}: {AssignmentGroupId}," +
             $"\n{nameof(DueDateRequired)}: {DueDateRequired}," +
             $"\n{nameof(AllowedExtensions)}: {AllowedExtensions?.ToPrettyString()}," +
             $"\n{nameof(MaxNameLength)}: {MaxNameLength}," +
             $"\n{nameof(TurnitinEnabled)}: {TurnitinEnabled}," +
             $"\n{nameof(VeriCiteEnabled)}: {VeriCiteEnabled}," +
             $"\n{nameof(TurnitinSettings)}: {TurnitinSettings}," +
             $"\n{nameof(GradeGroupStudentsIndividually)}: {GradeGroupStudentsIndividually}," +
             $"\n{nameof(ExternalToolTagAttributes)}: {ExternalToolTagAttributes}," +
             $"\n{nameof(PeerReviews)}: {PeerReviews}," +
             $"\n{nameof(AutomaticPeerReviews)}: {AutomaticPeerReviews}," +
             $"\n{nameof(PeerReviewCount)}: {PeerReviewCount}," +
             $"\n{nameof(PeerReviewsAssignAt)}: {PeerReviewsAssignAt}," +
             $"\n{nameof(IntraGroupPeerReviews)}: {IntraGroupPeerReviews}," +
             $"\n{nameof(GroupCategoryId)}: {GroupCategoryId}," +
             $"\n{nameof(NeedsGradingCount)}: {NeedsGradingCount}," +
             $"\n{nameof(NeedsGradingCountBySection)}: {NeedsGradingCountBySection?.ToPrettyString()}," +
             $"\n{nameof(Position)}: {Position}," +
             $"\n{nameof(PostToSis)}: {PostToSis}," +
             $"\n{nameof(IntegrationId)}: {IntegrationId}," +
             $"\n{nameof(IntegrationData)}: {IntegrationData}," +
             $"\n{nameof(Muted)}: {Muted}," +
             $"\n{nameof(PointsPossible)}: {PointsPossible}," +
             $"\n{nameof(SubmissionTypes)}: {SubmissionTypes.ToPrettyString()}," +
             $"\n{nameof(HasSubmittedSubmissions)}: {HasSubmittedSubmissions}," +
             $"\n{nameof(GradingType)}: {GradingType}," +
             $"\n{nameof(GradingStandardId)}: {GradingStandardId}," +
             $"\n{nameof(Published)}: {Published}," +
             $"\n{nameof(Unpublishable)}: {Unpublishable}," +
             $"\n{nameof(OnlyVisibleToOverrides)}: {OnlyVisibleToOverrides}," +
             $"\n{nameof(LockedForUser)}: {LockedForUser}," +
             $"\n{nameof(LockInfo)}: {LockInfo}," +
             $"\n{nameof(LockExplanation)}: {LockExplanation}," +
             $"\n{nameof(QuizId)}: {QuizId}," +
             $"\n{nameof(AnonymousSubmissions)}: {AnonymousSubmissions}," +
             $"\n{nameof(DiscussionTopic)}: {DiscussionTopic}," +
             $"\n{nameof(FreezeOnCopy)}: {FreezeOnCopy}," +
             $"\n{nameof(Frozen)}: {Frozen}," +
             $"\n{nameof(FrozenAttributes)}: {FrozenAttributes?.ToPrettyString()}," +
             $"\n{nameof(Submission)}: {Submission}," +
             $"\n{nameof(UseRubricForGrading)}: {UseRubricForGrading}," +
             $"\n{nameof(RubricSettings)}: {RubricSettings}," +
             $"\n{nameof(Rubric)}: {Rubric?.ToPrettyString()}," +
             $"\n{nameof(AssignmentVisibility)}: {AssignmentVisibility?.ToPrettyString()}," +
             $"\n{nameof(Overrides)}: {Overrides?.ToPrettyString()}," +
             $"\n{nameof(OmitFromFinalGrade)}: {OmitFromFinalGrade}," +
             $"\n{nameof(ModeratedGrading)}: {ModeratedGrading}," +
             $"\n{nameof(GraderCount)}: {GraderCount}," +
             $"\n{nameof(FinalGraderId)}: {FinalGraderId}," +
             $"\n{nameof(GraderCommentsVisibleToGraders)}: {GraderCommentsVisibleToGraders}," +
             $"\n{nameof(GradersAnonymousToGraders)}: {GradersAnonymousToGraders}," +
             $"\n{nameof(GraderNamesVisibleToFinalGrader)}: {GraderNamesVisibleToFinalGrader}," +
             $"\n{nameof(AnonymousGrading)}: {AnonymousGrading}," +
             $"\n{nameof(AllowedAttempts)}: {AllowedAttempts}").Indent(4) +
            "\n}");
 }
コード例 #24
0
        //public string RootFolder
        //{
        //    get;
        //    set;
        //}

        //public string DisplayFolder
        //{
        //    get;
        //    set;
        //}

        public bool IsExtAllowed(string extension)
        {
            return(AllowedExtensions.Contains(extension.ToLower()));
        }
コード例 #25
0
ファイル: PhotoUpload.cs プロジェクト: petrj/PhotoUpload
        private void UploadFolderToAlbum(DirectoryInfo directory, bool reupload = false)
        {
            try
            {
                Logger.Info($"Uploading folder {directory.Name}");

                // looking in journal
                var alreadyUploadedJournalItem = _uploadedJournal.Directory(directory.FullName);
                if (alreadyUploadedJournalItem != null)
                {
                    if (reupload)
                    {
                        Logger.Warning($"Reuploading folder {directory.FullName} with id {alreadyUploadedJournalItem.AlbumId}");
                    }
                    else
                    {
                        Logger.Warning($"Folder {directory.FullName} is already uploaded with id {alreadyUploadedJournalItem.AlbumId}");
                        return;
                    }
                }

                // https://stackoverflow.com/questions/7039580/multiple-file-extensions-searchpattern-for-system-io-directory-getfiles/7039649
                var files = Directory.GetFiles(directory.FullName, "*.*", SearchOption.TopDirectoryOnly)
                            .Where(f => AllowedExtensions.Contains(Path.GetExtension(f).ToLower())).ToList();

                Logger.Info($"Files found: {files.Count}");

                if (files.Count == 0)
                {
                    return;
                }

                files.Sort();

                string albumId;

                if (alreadyUploadedJournalItem != null)
                {
                    // album is already created
                    albumId = alreadyUploadedJournalItem.AlbumId;
                }
                else
                {
                    //  creating album
                    var alb = GAPIAlbum.CreateAlbum(_accountConnection, directory.Name);
                    albumId = alb.id;

                    AddToJournal(directory.FullName, albumId);
                }

                // batch upload
                var batchCount = 20;

                var fileTokensBatch = new List <Dictionary <string, string> >();

                var actualBatch = new Dictionary <string, string>();

                var fIndex = 0;
                foreach (var f in files)
                {
                    var fi = new FileInfo(f);
                    if (fi.Length == 0)
                    {
                        Logger.Warning($"Skipping empty file ({f})");
                        continue;
                    }

                    //  uploading file

                    var uploadToken = _accountConnection.UploadFile(f);

                    if (string.IsNullOrEmpty(uploadToken))
                    {
                        Logger.Warning($"Empty upload file token for file ({f})");
                        continue;
                    }

                    actualBatch.Add(uploadToken, Path.GetFileName(f));

                    fIndex++;
                    if (fIndex > batchCount)
                    {
                        if (actualBatch.Count > 0)
                        {
                            fileTokensBatch.Add(actualBatch);
                            actualBatch = new Dictionary <string, string>();
                        }
                        fIndex = 0;
                    }
                }

                if (actualBatch.Count > 0)
                {
                    fileTokensBatch.Add(actualBatch);
                }

                if (fileTokensBatch.Count > 0)
                {
                    foreach (var batch in fileTokensBatch)
                    {
                        var uploadedItems = GAPIAlbum.AddMediaItemsToAlbum(_accountConnection, albumId, batch);
                    }
                }
                else
                {
                    Logger.Info($"No file uploaded");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
コード例 #26
0
        /// <summary>
        /// method returns a list of Selection
        /// </summary>
        async Task HandleSelection(IFileListEntry[] files)
        {
            // locals
            UploadedFileInfo uploadedFileInfo = null;
            bool             abort            = false;

            // locals
            MemoryStream ms = null;

            var file = files.FirstOrDefault();

            if (file != null)
            {
                try
                {
                    // the partialGuid is need to ensure uniqueness
                    string partialGuid = Guid.NewGuid().ToString().Substring(0, PartialGuidLength);

                    // create the uploadedFileInfo
                    uploadedFileInfo = new UploadedFileInfo(file, partialGuid, AppendPartialGuid, UploadFolder);

                    // if the file is too large
                    if ((MaxFileSize > 0) && (file.Size > MaxFileSize))
                    {
                        // Show the FileTooLargeMessage
                        status = FileTooLargeMessage;

                        // Upload was aborted
                        uploadedFileInfo.Aborted      = true;
                        uploadedFileInfo.ErrorMessage = FileTooLargeMessage;
                        uploadedFileInfo.Exception    = new Exception("The file uploaded was too large.");
                    }
                    else
                    {
                        // Create a new instance of a 'FileInfo' object.
                        FileInfo fileInfo = new FileInfo(file.Name);

                        // Set the extension. The ToLower is for just in case. I don't know if it's even possible for an extension to be upper case
                        uploadedFileInfo.Extension = fileInfo.Extension.ToLower();

                        // if FilterByExtension is true and the AllowedExtensions text exists
                        if ((FilterByExtension) && (!string.IsNullOrWhiteSpace(AllowedExtensions)))
                        {
                            // If the allowed extensions
                            abort = !AllowedExtensions.ToLower().Contains(fileInfo.Extension);
                        }

                        // Set aborted to true
                        uploadedFileInfo.Aborted = abort;

                        // if we should continue
                        if (!abort)
                        {
                            // create the memoryStream
                            ms = new MemoryStream();

                            // await for the data to be copied to the memory stream
                            await file.Data.CopyToAsync(ms);

                            // Check for abort 1 more time
                            uploadedFileInfo = CheckSize(fileInfo.Extension, ms, uploadedFileInfo);

                            // if abort
                            if (uploadedFileInfo.Aborted)
                            {
                                // Do not process due to size is not valid, message has already been set
                                abort = true;
                            }
                        }

                        // if we should continue
                        if (!abort)
                        {
                            // save the file using the FullName (If AppendPartialGuid is still true, than the Name.PartialGuid is the FullName
                            using (FileStream fileStream = new FileStream(Path.Combine(UploadFolder, uploadedFileInfo.FullName), FileMode.Create, FileAccess.Write))
                            {
                                ms.WriteTo(fileStream);
                            }

                            // if there is a CustomSave
                            if (!String.IsNullOrWhiteSpace(CustomSuccessMessage))
                            {
                                // Show the CustomSuccessMessage
                                status = CustomSuccessMessage;
                            }
                            else
                            {
                                // set the status
                                status = $"Saved file {file.Size} bytes from {file.Name}";
                            }

                            // Set additional properties for UploadFileInfo from this component; these values may be null.
                            uploadedFileInfo.CustomId = CustomId;
                            uploadedFileInfo.Tag      = Tag;

                            // The upload has completed
                            UploadComplete = true;
                        }
                        else
                        {
                            // If a CustomExtensionMessage has been set
                            if (!string.IsNullOrWhiteSpace(CustomExtensionMessage))
                            {
                                // Display the Custom extension doesn't validate message
                                uploadedFileInfo.ErrorMessage = CustomExtensionMessage;
                            }
                            else
                            {
                                // Can't think of a better message than this yet, just woke up
                                uploadedFileInfo.ErrorMessage = "The file uploaded is an invalid extension.";
                            }

                            // Show the exception
                            uploadedFileInfo.Exception = new Exception(uploadedFileInfo.ErrorMessage);
                        }
                    }
                }
                catch (Exception error)
                {
                    // Upload was aborted
                    uploadedFileInfo.Aborted = true;

                    // Store the Exception
                    uploadedFileInfo.Exception = error;

                    // if a CustomErrorMessage is set
                    if (!String.IsNullOrWhiteSpace(CustomErrorMessage))
                    {
                        // Show the custom error message
                        status = CustomErrorMessage;
                    }
                    else
                    {
                        // show the full error
                        status = error.ToString();
                    }

                    // set the error message
                    uploadedFileInfo.ErrorMessage = status;
                }
                finally
                {
                    // Notify the caller the upload was successful or aborted due to an error
                    FileUploaded(uploadedFileInfo);
                }
            }
        }
コード例 #27
0
        public async Task <IActionResult> UploadPhoto([FromForm] PhotoFile file)
        {
            var photo  = file.Photo;
            var sizeMB = photo.Length / 1024 / 1000;

            if (sizeMB > 10)
            {
                return(StatusCode(400, new ErrorDetails()
                {
                    errorId = ErrorList.WrongSize.Id,
                    errorMessage = ErrorList.WrongSize.Description
                }));
            }

            int userId  = int.Parse(HttpContext.User.Claims.FirstOrDefault(c => c.Type == claimTypes.Id.ToString()).Value);
            int?albumId = file.AlbumId;

            if (albumId > 0)
            {
                if (!db.CheckAlbumExists((int)albumId, userId))
                {
                    return(StatusCode(403, new ErrorDetails()
                    {
                        errorId = ErrorList.UnauthorizedAction.Id, errorMessage = ErrorList.UnauthorizedAction.Description
                    }.ToString()));
                }
            }

            var extension = Path.GetExtension(photo.FileName).Replace(".", "");

            if (!AllowedExtensions.Contains(extension))
            {
                return(BadRequest(new ErrorDetails()
                {
                    errorId = ErrorList.InputDataError.Id, errorMessage = ErrorList.InputDataError.Description
                }.ToString()));
            }
            ;

            var imageName   = Guid.NewGuid().ToString().Replace("-", "");
            var newFilename = $"{imageName}.{extension}";
            var thumbName   = $"{imageName}_thumb.{extension}";

            var additionalPath = $"/{userId}";
            var newImagePath   = $"{additionalPath}/{newFilename}";
            var newThumbPath   = $"{additionalPath}/{thumbName}";

            db.AddPhoto(newFilename, userId, albumId, newImagePath, newThumbPath, thumbName);

            var path      = storage + newImagePath;
            var thumbPath = storage + newThumbPath;

            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                await photo.CopyToAsync(fileStream);
            }

            var resizedThumb = helper.ResizeImage(Image.FromStream(photo.OpenReadStream()));

            if (!Directory.Exists(Path.GetDirectoryName(thumbPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(thumbPath));
            }

            helper.SaveImage(resizedThumb, thumbPath);

            return(Ok(new { response = new { fileName = newFilename } }));
        }
コード例 #28
0
        /// <summary>
        /// Validates that a required binary data have been send on the request
        /// </summary>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (AllowedBlobMaxLength <= 0)
            {
                throw new ArgumentException("The AllowedBlobMaxLength can't be zero or less.");
            }
            if (AllowedMinimunFiles <= 0)
            {
                throw new ArgumentException("The AllowedMinimunFiles can't be zero or less.");
            }
            if (AllowedMaximunFiles <= 0)
            {
                throw new ArgumentException("The AllowedMaximunFiles can't be zero or less.");
            }
            var formFiles = filterContext.HttpContext.Request.Form.Files;
            var blobs     = string.IsNullOrWhiteSpace(FormFieldName) ? formFiles : formFiles.Where(w => w.Name == FormFieldName);

            if (!blobs.Any())
            {
                filterContext.Result = new ApiResponse <string>()
                {
                    Status = ApiResponseStatus.Failed, Message = "FileUploadRequired"
                }.ToJson();
            }
            else
            {
                if (blobs.Count() < AllowedMinimunFiles)
                {
                    filterContext.Result = new ApiResponse <string>()
                    {
                        Status = ApiResponseStatus.Failed, Message = "TheCountOfFilesUploadedHasExceededTheMaximunAllowedFiles"
                    }.ToJson();
                }
                if (blobs.Count() > AllowedMaximunFiles)
                {
                    filterContext.Result = new ApiResponse <string>()
                    {
                        Status = ApiResponseStatus.Failed, Message = "TheCountOfFilesUploadedIsLessThanTheMinimunAllowedFiles"
                    }.ToJson();
                }
                foreach (var blob in blobs)
                {
                    if (blob == null || blob.Length == 0)
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "FileUploadRequired", Data = blob.Name
                        }.ToJson();
                    }
                    else if (blob.Length > AllowedBlobMaxLength)
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileHasExceededTheLargestSizeAllowed", Data = blob.Name
                        }.ToJson();
                    }
                    else if (AllowedContentTypes != null && AllowedContentTypes.Any() && !AllowedContentTypes.Contains(blob.ContentType))
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileDoesNotHaveTheExpectedContentType", Data = blob.Name
                        }.ToJson();
                    }
                    else if (AllowedExtensions != null && AllowedExtensions.Any() && !AllowedExtensions.Contains(Path.GetExtension(blob.FileName)))
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileDoesNotHaveTheExpectedExtension", Data = blob.Name
                        }.ToJson();
                    }
                    else if (AllowedContentDispositions != null && AllowedContentDispositions.Any() && !AllowedContentDispositions.Contains(blob.ContentDisposition))
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileDoesNotHaveTheExpectedContentDisposition", Data = blob.Name
                        }.ToJson();
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }
コード例 #29
0
 public bool IsExtensionAllowed(string ext)
 {
     return(AllowedExtensions.Contains("*") || AllowedExtensions.Contains(ext));
 }