private IReadOnlyCollection <FlowComponent> getUploadComponents(
            int fileCollectionId, IReadOnlyCollection <BlobFile> files, DisplaySetup displaySetup, string postBackIdBase,
            Action <RsFile, Validator> uploadValidationMethod, NewFileNotificationMethod fileCreatedOrReplacedNotifier)
        {
            RsFile file = null;
            var    dm   = PostBack.CreateFull(
                id: PostBack.GetCompositeId(postBackIdBase, "add"),
                firstModificationMethod: () => {
                if (file == null)
                {
                    return;
                }

                var existingFile = files.SingleOrDefault(i => i.FileName == file.FileName);
                int newFileId;
                if (existingFile != null)
                {
                    BlobStorageStatics.SystemProvider.UpdateFile(
                        existingFile.FileId,
                        file.FileName,
                        file.Contents,
                        BlobStorageStatics.GetContentTypeForPostedFile(file));
                    newFileId = existingFile.FileId;
                }
                else
                {
                    newFileId = BlobStorageStatics.SystemProvider.InsertFile(
                        fileCollectionId,
                        file.FileName,
                        file.Contents,
                        BlobStorageStatics.GetContentTypeForPostedFile(file));
                }

                fileCreatedOrReplacedNotifier?.Invoke(newFileId);
                EwfPage.AddStatusMessage(StatusMessageType.Info, "File uploaded successfully.");
            });

            return(FormState.ExecuteWithDataModificationsAndDefaultAction(
                       dm.ToCollection(),
                       () => new StackList(
                           new FileUpload(
                               validationMethod: (postBackValue, validator) => {
                file = postBackValue;
                uploadValidationMethod?.Invoke(postBackValue, validator);
            }).ToFormItem()
                           .ToListItem()
                           .Append(new EwfButton(new StandardButtonStyle("Upload new file")).ToCollection().ToComponentListItem())).ToFormItem(
                           setup: new FormItemSetup(displaySetup: displaySetup),
                           label: "Select and upload a new file:".ToComponents())
                       .ToComponentCollection()));
        }
        private ControlList getUploadControlList()
        {
            var dm = PostBack.CreateFull(id: PostBack.GetCompositeId(postBackIdBase, "add"));

            RsFile file = null;
            var    fi   = FormItem.Create(
                "",
                new EwfFileUpload(),
                validationGetter: control => new EwfValidation(
                    (pbv, validator) => {
                BlobFileOps.ValidateUploadedFile(validator, control, acceptableFileExtensions, ValidateImage, AcceptOnlyImages);
                file = control.GetPostBackValue(pbv);
            },
                    dm));

            dm.AddModificationMethod(
                () => {
                if (file == null)
                {
                    return;
                }

                var existingFile = files.SingleOrDefault(i => i.FileName == file.FileName);
                int newFileId;
                if (existingFile != null)
                {
                    BlobFileOps.SystemProvider.UpdateFile(existingFile.FileId, file.FileName, file.Contents, BlobFileOps.GetContentTypeForPostedFile(file));
                    newFileId = existingFile.FileId;
                }
                else
                {
                    newFileId = BlobFileOps.SystemProvider.InsertFile(fileCollectionId, file.FileName, file.Contents, BlobFileOps.GetContentTypeForPostedFile(file));
                }

                if (NewFileNotificationMethod != null)
                {
                    NewFileNotificationMethod(newFileId);
                }
                EwfPage.AddStatusMessage(StatusMessageType.Info, "File uploaded successfully.");
            });

            return(ControlList.CreateWithControls(
                       true,
                       "Select and upload a new file:",
                       fi.ToControl(),
                       new PostBackButton(dm, new ButtonActionControlStyle("Upload new file"), false)));
        }
        /// <summary>
        /// Gets the post back value.
        /// </summary>
        public RsFile GetPostBackValue(PostBackValueDictionary postBackValues)
        {
            if (postBackValue == null)
            {
                var value = formValue.GetValue(postBackValues);
                if (value == null)
                {
                    return(null);
                }

                using (var ms = new MemoryStream()) {
                    value.InputStream.CopyTo(ms);
                    postBackValue = new RsFile(ms.ToArray(), Path.GetFileName(value.FileName), contentType: value.ContentType);
                }
            }
            return(postBackValue);
        }
Esempio n. 4
0
        public static string GetRStTF(int rid)
        {
            DataTable     dt   = Mydb.ExecuteReadertoDataTable("select rsf.FILE_ADRESS,rst.RS_TEXT from REQUEST_STATUS_FILE_SUPPLIERS rsf,REQUEST_STATUS_TEXT_SUPPLIERS rst where REQUEST_ID=@rid and rst.RST_ID=rsf.RST_ID", new SqlParameter[] { new SqlParameter("@rid", rid) }, CommandType.Text);
            List <RsFile> rsfs = new List <RsFile>();

            foreach (DataRow item in dt.Rows)
            {
                RsFile rsf = new RsFile();
                rsf.RS_TEXT  = item["RS_TEXT"].ToString();
                rsf.ImgAdres = item["FILE_ADRESS"].ToString();
                rsfs.Add(rsf);
            }

            JavaScriptSerializer js = new JavaScriptSerializer();

            return(js.Serialize(rsfs));
        }
Esempio n. 5
0
        /// <summary>
        /// If file is null, this will be a no-op.
        /// Pass null for acceptableFileExtensions if there is no restriction on file extension.
        /// PerformAdditionalImageValidation cannot be null but may be an empty delegate.
        /// </summary>
        /// <param name="validator"></param>
        /// <param name="file"></param>
        /// <param name="acceptableFileExtensions">Prevents the user from uploading a file of a type other than those provided. File type constants found in
        /// EnterpriseWebLibrary.FileExtensions. Do not use this to force the file to be a specific type of file, such as an image (which consists of several file
        /// extensions). Instead, use mustBeRenderableImage.</param>
        /// <param name="mustBeRenderableImage">Pass true to only accept images (of any renderable type - jpgs, pngs, but not nefs).</param>
        public static void ValidateUploadedFile(Validator validator, RsFile file, string[] acceptableFileExtensions, bool mustBeRenderableImage)
        {
            if (file == null)
            {
                return;
            }

            // Perform generic file validation.
            if (acceptableFileExtensions != null && !FileExtensions.MatchesAGivenExtension(file.FileName, acceptableFileExtensions))
            {
                validator.NoteErrorAndAddMessage(Translation.UnacceptableFileExtension + " " + acceptableFileExtensions.GetCommaDelimitedStringFromCollection());
                // Don't bother trying to see if it's an image and parse the image. The file extension message be more detailed than the messages those errors produce.
                return;
            }

            // Perform image-specific validation if necessary.
            if (mustBeRenderableImage)
            {
                // Make sure it is an image according to its content type.
                if (!ContentTypes.IsImageType(BlobStorageStatics.GetContentTypeForPostedFile(file)))
                {
                    validator.NoteErrorAndAddMessage("Please upload a valid image file.");
                }
                else
                {
                    // Make sure it is an image type that we understand. Also perform optional custom validation.
                    try {
                        using (var stream = new MemoryStream(file.Contents))
                            System.Drawing.Image.FromStream(stream);
                    }
                    catch (ArgumentException) {
                        // If we end up in this catch block, it means that System.Drawing.Image does not understand our image. Since we already know that our content type
                        // is image at this point, this usually means that the file is some sort of unsupported image format, like NEF.
                        validator.NoteErrorAndAddMessage("The uploaded image file is in an unsupported format.");
                    }
                }
            }
        }
 public static string HandleUploadedFiles(string fileUploaderIdentifier, string parameters, RsFile file)
 {
     return("");
 }
Esempio n. 7
0
        public BlobFileManager(
            int?fileCollectionId, bool requireUploadIfNoFile, Action <int> idSetter, out Action modificationMethod, BlobFileManagerSetup setup = null)
        {
            setup = setup ?? BlobFileManagerSetup.Create();
            var file = fileCollectionId != null?BlobStorageStatics.GetFirstFileFromCollection(fileCollectionId.Value) : null;

            var components = new List <FlowComponent>();

            if (file != null)
            {
                var download = new EwfButton(
                    new StandardButtonStyle(Translation.DownloadExisting + " (" + file.FileName + ")", buttonSize: ButtonSize.ShrinkWrap),
                    behavior: new PostBackBehavior(
                        postBack: PostBack.CreateFull(
                            id: PostBack.GetCompositeId("ewfFile", file.FileId.ToString()),
                            actionGetter: () => {
                    // Refresh the file here in case a new one was uploaded on the same post-back.
                    return(new PostBackAction(
                               new PageReloadBehavior(
                                   secondaryResponse: new SecondaryResponse(
                                       new BlobFileResponse(BlobStorageStatics.GetFirstFileFromCollection(fileCollectionId.Value).FileId, () => true),
                                       false))));
                })));
                components.Add(download);
            }
            else if (!setup.OmitNoExistingFileMessage)
            {
                components.Add(new GenericPhrasingContainer(Translation.NoExistingFile.ToComponents()));
            }

            RsFile uploadedFile           = null;
            var    fileUploadDisplayedPmv = new PageModificationValue <string>();

            components.AddRange(
                new FileUpload(
                    displaySetup: fileUploadDisplayedPmv.ToCondition(bool.TrueString.ToCollection()).ToDisplaySetup(),
                    validationPredicate: setup.UploadValidationPredicate,
                    validationErrorNotifier: setup.UploadValidationErrorNotifier,
                    validationMethod: (postBackValue, validator) => {
                if (requireUploadIfNoFile && file == null && postBackValue == null)
                {
                    validator.NoteErrorAndAddMessage(Translation.PleaseUploadAFile);
                    setup.UploadValidationErrorNotifier?.Invoke();
                    return;
                }

                uploadedFile = postBackValue;
                setup.UploadValidationMethod?.Invoke(postBackValue, validator);
            }).ToFormItem()
                .ToComponentCollection());
            var fileUploadDisplayedHiddenFieldId = new HiddenFieldId();

            if (file != null)
            {
                components.Add(
                    new EwfButton(
                        new StandardButtonStyle(Translation.ClickHereToReplaceExistingFile, buttonSize: ButtonSize.ShrinkWrap),
                        displaySetup: fileUploadDisplayedPmv.ToCondition(bool.FalseString.ToCollection()).ToDisplaySetup(),
                        behavior: new ChangeValueBehavior(fileUploadDisplayedHiddenFieldId, bool.TrueString)));
            }

            children = new GenericFlowContainer(
                BlobManagementStatics.GetThumbnailControl(file, setup.ThumbnailResourceGetter)
                .Append <FlowComponent>(new StackList(from i in components select i.ToCollection().ToComponentListItem()))
                .Materialize(),
                displaySetup: setup.DisplaySetup,
                classes: setup.Classes,
                etherealContent: new EwfHiddenField((file == null).ToString(), id: fileUploadDisplayedHiddenFieldId, pageModificationValue: fileUploadDisplayedPmv)
                .PageComponent.ToCollection()).ToCollection();

            modificationMethod = () => {
                if (fileCollectionId == null)
                {
                    fileCollectionId = BlobStorageStatics.SystemProvider.InsertFileCollection();
                }

                if (uploadedFile != null)
                {
                    BlobStorageStatics.SystemProvider.DeleteFilesLinkedToFileCollection(fileCollectionId.Value);
                    BlobStorageStatics.SystemProvider.InsertFile(
                        fileCollectionId.Value,
                        uploadedFile.FileName,
                        uploadedFile.Contents,
                        BlobStorageStatics.GetContentTypeForPostedFile(uploadedFile));
                }

                idSetter(fileCollectionId.Value);
            };
        }
Esempio n. 8
0
 /// <summary>
 /// Returns the content type of the given HttpPostedFile.
 /// </summary>
 // This implementation simply returns the media type provided by the client, which makes it vulnerable to spoofing. The only way around this is to determine
 // the media type by looking at the contents of the file.
 internal static string GetContentTypeForPostedFile(RsFile file)
 {
     return(file.ContentType);
 }
Esempio n. 9
0
        /// <summary>
        /// Returns the content type of the given HttpPostedFile.
        /// </summary>
        /// There is no such thing as an official mapping of file extentions to content types or vice versa.
        /// Windows has a one-one mapping in the registry, which is how the client's (Windows) computer determines the file type.
        /// Windows determines the content type through no other means than the file extension. This also means that
        /// different clients can have different content types and are even able to spoof the content-type. HttpPostedFile does nothing more
        /// than determine the content-type given by the client headers. Because of this, I think that would should
        /// first be consulting our official mappings of file extensions to content types, and then fall back on the .NET provided method.
        /// Maybe we should never be trusting the client's content-type, since it's conceivable it could lead to a buffer-overflow attack.
        /// We could fall back to consulting the server's content-type mappings instead of trusting the client at all, but this is flawed too
        /// since all it takes to make us determine the file to be another content-type is to change the extension.
        internal static string GetContentTypeForPostedFile(RsFile file)
        {
            var type = ContentTypes.GetContentType(file.FileName);

            return(type != String.Empty ? type : file.ContentType);
        }