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()));
        }
Пример #2
0
        // NOTE: Use this from blob file manager, etc.
        /// <summary>
        /// Returns a link to download a file with the given file collection ID.
        /// If no file is associated with the given file collection ID, returns a literal control with textIfNoFile text.
        /// The file name is used as the label unless labelOverride is specified.
        /// SystemBlobFileManagementProvider must be implemented.
        /// </summary>
        public static IReadOnlyCollection <PhrasingComponent> GetFileButton(int fileCollectionId, string labelOverride = null, string textIfNoFile = "")
        {
            var file = BlobStorageStatics.GetFirstFileFromCollection(fileCollectionId);

            if (file == null)
            {
                return(textIfNoFile.ToComponents());
            }
            return(new EwfButton(
                       new StandardButtonStyle(labelOverride ?? file.FileName, buttonSize: ButtonSize.ShrinkWrap),
                       behavior: new PostBackBehavior(
                           postBack: PostBack.CreateFull(
                               id: PostBack.GetCompositeId("ewfFile", file.FileId.ToString()),
                               actionGetter: () => new PostBackAction(
                                   new PageReloadBehavior(
                                       secondaryResponse: new SecondaryResponse(
                                           new BlobFileResponse(BlobStorageStatics.GetFirstFileFromCollection(fileCollectionId).FileId, () => true),
                                           false)))))).ToCollection());
        }
Пример #3
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.");
                    }
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Initializes the system. This includes loading application settings from the configuration file. The application name should be scoped within the system.
        /// For non web applications, this method must be called directly from the main executable assembly and not from a supporting library.
        ///
        /// To debug this method, create a folder called C:\AnyoneFullControl and give Everyone full control. A file will appear in that folder explaining how far
        /// it got in init.
        /// </summary>
        /// <param name="globalInitializer">The system's global initializer. Do not pass null.</param>
        /// <param name="appName"></param>
        /// <param name="isClientSideApp"></param>
        /// <param name="assemblyFolderPath">Pass a nonempty string to override the assembly folder path, which is used to locate the installation folder. Use with
        /// caution.</param>
        /// <param name="mainDataAccessStateGetter">A method that returns the current main data-access state whenever it is requested, including during this
        /// InitStatics call. Do not allow multiple threads to use the same state at the same time. If you pass null, the data-access subsystem will not be
        /// available in the application.</param>
        /// <param name="useLongDatabaseTimeouts">Pass true if the application is a background process that can tolerate slow database access.</param>
        public static void InitStatics(
            SystemInitializer globalInitializer, string appName, bool isClientSideApp, string assemblyFolderPath = "",
            Func <DataAccessState> mainDataAccessStateGetter = null, bool useLongDatabaseTimeouts = false)
        {
            var initializationLog = "Starting init";

            try {
                if (initialized)
                {
                    throw new ApplicationException("This class can only be initialized once.");
                }

                if (globalInitializer == null)
                {
                    throw new ApplicationException("The system must have a global initializer.");
                }

                // Initialize these before the exception handling block below because it's reasonable for the exception handling to depend on them.
                ConfigurationStatics.Init(assemblyFolderPath, globalInitializer.GetType(), appName, isClientSideApp, ref initializationLog);
                EmailStatics.Init();
                TelemetryStatics.Init();

                // Setting the initialized flag to true must be done before executing the secondary init block below so that exception handling works.
                initialized        = true;
                initializationLog += Environment.NewLine + "Succeeded in primary init.";
            }
            catch (Exception e) {
                initializationLog += Environment.NewLine + e;
                EwlStatics.EmergencyLog("Initialization log", initializationLog);
                throw;
            }

            try {
                CultureInfo.DefaultThreadCurrentCulture = Cultures.EnglishUnitedStates;

                var asposePdfLicensePath = EwlStatics.CombinePaths(ConfigurationStatics.InstallationConfiguration.AsposeLicenseFolderPath, "Aspose.PDF.lic");
                if (File.Exists(asposePdfLicensePath))
                {
                    new Aspose.Pdf.License().SetLicense(asposePdfLicensePath);
                }
                var asposeWordsLicensePath = EwlStatics.CombinePaths(ConfigurationStatics.InstallationConfiguration.AsposeLicenseFolderPath, "Aspose.Words.lic");
                if (File.Exists(asposeWordsLicensePath))
                {
                    new Aspose.Words.License().SetLicense(asposeWordsLicensePath);
                }

                AppMemoryCache.Init();
                BlobStorageStatics.Init();
                DataAccessStatics.Init();
                DataAccessState.Init(mainDataAccessStateGetter, useLongDatabaseTimeouts);
                EncryptionOps.Init();
                HtmlBlockStatics.Init();
                UserManagementStatics.Init();

                GlobalInitializationOps.globalInitializer = globalInitializer;
                globalInitializer.InitStatics();
            }
            catch (Exception e) {
                secondaryInitFailed = true;

                // Suppress all exceptions since they would prevent apps from knowing that primary initialization succeeded. EWF apps need to know this in order to
                // automatically restart themselves. Other apps could find this knowledge useful as well.
                try {
                    TelemetryStatics.ReportError("An exception occurred during application initialization:", e);
                }
                catch {}
            }
        }
Пример #5
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);
            };
        }