internal static FormAction GetHyperlinkPostBackAction(ResourceInfo destination)
        {
            var id = PostBack.GetCompositeId("ewfLink", destination.GetUrl());

            return(new PostBackFormAction(
                       EwfPage.Instance.GetPostBack(id) ?? PostBack.CreateFull(id: id, actionGetter: () => new PostBackAction(destination))));
        }
Exemplo n.º 2
0
 private ActionComponentSetup getExportAction(IEnumerable <object> headers, List <IEnumerable <object> > tableData) =>
 new ButtonSetup(
     "Export",
     behavior: new PostBackBehavior(
         postBack: PostBack.CreateFull(
             id: PostBack.GetCompositeId(setup.PostBackIdBase, "export"),
             actionGetter: () => new PostBackAction(
                 new PageReloadBehavior(
                     secondaryResponse: new SecondaryResponse(
                         () => EwfResponse.Create(
                             ContentTypes.Csv,
                             new EwfResponseBodyCreator(
                                 writer => {
     var csv = new CsvFileWriter();
     csv.AddValuesToLine(headers.ToArray());
     csv.WriteCurrentLineToFile(writer);
     foreach (var td in tableData)
     {
         csv.AddValuesToLine(td.ToArray());
         csv.WriteCurrentLineToFile(writer);
     }
 }),
                             () => "{0} {1}".FormatWith(
                                 setup.ExportFileName,
                                 AppRequestState.RequestTime.InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()).ToDateTimeUnspecified()) +
                             FileExtensions.Csv)))))));
Exemplo n.º 3
0
        private Block getExportButton(IEnumerable <object> headers, List <IEnumerable <object> > tableData)
        {
            var block =
                new Block(
                    new PostBackButton(
                        PostBack.CreateFull(
                            id: PostBack.GetCompositeId(setup.PostBackIdBase, "export"),
                            actionGetter: () => new PostBackAction(
                                new SecondaryResponse(
                                    () => EwfResponse.Create(
                                        ContentTypes.Csv,
                                        new EwfResponseBodyCreator(
                                            writer => {
                var csv = new CsvFileWriter();
                csv.AddValuesToLine(headers.ToArray());
                csv.WriteCurrentLineToFile(writer);
                foreach (var td in tableData)
                {
                    csv.AddValuesToLine(td.ToArray());
                    csv.WriteCurrentLineToFile(writer);
                }
            }),
                                        () => "{0} {1}".FormatWith(setup.ExportFileName, DateTime.Now) + FileExtensions.Csv)))),
                        new TextActionControlStyle("Export"),
                        usesSubmitBehavior: false));

            block.Style.Add("text-align", "right");
            return(block);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Creates a chart setup object.
 /// </summary>
 /// <param name="chartType"></param>
 /// <param name="xAxisTitle">The title of the X axis. Do not pass null.</param>
 /// <param name="labels">The labels for the X axis. There must be exactly as many elements as there are in each series.</param>
 /// <param name="exportFileName">Used to create a meaningful file name when exporting the data.</param>
 /// <param name="postBackIdBase">Do not pass null.</param>
 /// <param name="maxXValues">The number of values to display on the x axis. This menas only the last <paramref name="maxXValues"/> values are displayed.
 /// </param>
 public ChartSetup(
     ChartType chartType, string xAxisTitle, IEnumerable <string> labels, string exportFileName, string postBackIdBase = "", int maxXValues = 16)
 {
     PostBackIdBase = PostBack.GetCompositeId("ewfChart", postBackIdBase);
     ChartType      = chartType;
     XAxisTitle     = xAxisTitle;
     Labels         = labels;
     MaxXValues     = maxXValues;
     ExportFileName = exportFileName;
 }
        /// <summary>
        /// Creates a file collection manager.
        /// </summary>
        /// <param name="fileCollectionId"></param>
        /// <param name="displaySetup"></param>
        /// <param name="postBackIdBase">Do not pass null.</param>
        /// <param name="sortByName"></param>
        /// <param name="thumbnailResourceGetter">A function that takes a file ID and returns the corresponding thumbnail resource. Do not return null.</param>
        /// <param name="openedFileIds">The file IDs that should not be marked with a UI element drawing the user’s attention to the fact that they haven’t read it.
        /// All other files not in this collection will be marked. The collection can be null, and will result as nothing being shown as new.</param>
        /// <param name="unopenedFileOpenedNotifier">A method that executes when an unopened file is opened. Use to update the app’s database with an indication
        /// that the file has been seen by the user.</param>
        /// <param name="disableModifications">Pass true if there should be no way to upload or delete files.</param>
        /// <param name="uploadValidationMethod"></param>
        /// <param name="fileCreatedOrReplacedNotifier">A method that executes after a file is created or replaced.</param>
        /// <param name="filesDeletedNotifier">A method that executes after one or more files are deleted.</param>
        public BlobFileCollectionManager(
            int fileCollectionId, DisplaySetup displaySetup  = null, string postBackIdBase              = "", bool sortByName = false,
            Func <int, ResourceInfo> thumbnailResourceGetter = null, IEnumerable <int> openedFileIds    = null, MarkFileAsReadMethod unopenedFileOpenedNotifier = null,
            bool disableModifications = false, Action <RsFile, Validator> uploadValidationMethod        = null,
            NewFileNotificationMethod fileCreatedOrReplacedNotifier = null, Action filesDeletedNotifier = null)
        {
            postBackIdBase = PostBack.GetCompositeId("ewfFileCollection", postBackIdBase);

            var columnSetups = new List <EwfTableField>();

            if (thumbnailResourceGetter != null)
            {
                columnSetups.Add(new EwfTableField(size: 10.ToPercentage()));
            }
            columnSetups.Add(new EwfTableField(classes: new ElementClass("ewfOverflowedCell")));
            columnSetups.Add(new EwfTableField(size: 13.ToPercentage()));
            columnSetups.Add(new EwfTableField(size: 7.ToPercentage()));

            var table = EwfTable.Create(
                postBackIdBase: postBackIdBase,
                caption: "Files",
                selectedItemActions: disableModifications
                                                             ? null
                                                             : SelectedItemAction.CreateWithFullPostBackBehavior <int>(
                    "Delete Selected Files",
                    ids => {
                foreach (var i in ids)
                {
                    BlobStorageStatics.SystemProvider.DeleteFile(i);
                }
                filesDeletedNotifier?.Invoke();
                EwfPage.AddStatusMessage(StatusMessageType.Info, "Selected files deleted successfully.");
            })
                .ToCollection(),
                fields: columnSetups);

            IReadOnlyCollection <BlobFile> files = BlobStorageStatics.SystemProvider.GetFilesLinkedToFileCollection(fileCollectionId);

            files = (sortByName ? files.OrderByName() : files.OrderByUploadedDateDescending()).Materialize();

            foreach (var file in files)
            {
                addFileRow(postBackIdBase, thumbnailResourceGetter, openedFileIds, unopenedFileOpenedNotifier, table, file);
            }

            children = files.Any() || !disableModifications
                                           ? table.Concat(
                !disableModifications
                ?getUploadComponents( fileCollectionId, files, displaySetup, postBackIdBase, uploadValidationMethod, fileCreatedOrReplacedNotifier )
                : Enumerable.Empty <FlowComponent>())
                       .Materialize()
                                           : Enumerable.Empty <FlowComponent>().Materialize();
        }
        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()));
        }
Exemplo n.º 7
0
 /// <summary>
 /// Creates a chart setup object.
 /// </summary>
 /// <param name="chartType"></param>
 /// <param name="aspectRatio">The aspect ratio (width divided by height) of the chart canvas.</param>
 /// <param name="labels">The labels for the X axis. There must be exactly as many elements as there are in each data set.</param>
 /// <param name="postBackIdBase">Do not pass null.</param>
 /// <param name="xAxisTitle">The title of the X axis. Do not pass null.</param>
 /// <param name="maxXValues">The number of values to display on the x axis. This menas only the last <paramref name="maxXValues"/> values are displayed.
 /// </param>
 /// <param name="yAxisTitle">The title of the Y axis. Do not pass null.</param>
 /// <param name="yAxisLabelFormatOptions">A JavaScript object containing number format options for the labels on the Y axis. It will be passed into
 /// Intl.NumberFormat as the options parameter. See
 /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat for more information.</param>
 /// <param name="omitTable">Pass true to omit the table containing the chart’s underlying data.</param>
 public ChartSetup(
     ChartType chartType, double aspectRatio, IEnumerable <string> labels, string postBackIdBase = "", string xAxisTitle = "", int maxXValues = 16,
     string yAxisTitle = "", JObject yAxisLabelFormatOptions = null, bool omitTable = false)
 {
     PostBackIdBase          = PostBack.GetCompositeId("ewfChart", postBackIdBase);
     ChartType               = chartType;
     AspectRatio             = aspectRatio;
     XAxisTitle              = xAxisTitle;
     Labels                  = labels;
     MaxXValues              = maxXValues;
     YAxisTitle              = yAxisTitle;
     YAxisLabelFormatOptions = yAxisLabelFormatOptions;
     OmitTable               = omitTable;
 }
Exemplo n.º 8
0
        /// <summary>
        /// Returns a link to download a file with the given file 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> GetFileButtonFromFileId(int fileId, string labelOverride = null, string textIfNoFile = "")
        {
            var file = BlobStorageStatics.SystemProvider.GetFile(fileId);

            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(fileId, () => true), false)))))).ToCollection());
        }
Exemplo n.º 9
0
        private FlowComponent getEntityNavListContainer()
        {
            if (entityUiSetup == null)
            {
                return(null);
            }

            var formItems = entityUiSetup.NavFormControls
                            .Select((control, index) => control.GetFormItem(PostBack.GetCompositeId("entity", "nav", index.ToString())))
                            .Materialize();
            var listItems = getActionListItems(entityUiSetup.NavActions).Concat(formItems.Select(i => i.ToListItem())).Materialize();

            if (!listItems.Any())
            {
                return(null);
            }

            return(new GenericFlowContainer(new LineList(listItems.Select(i => (LineListItem)i)).ToCollection(), classes: entityNavListContainerClass));
        }
Exemplo n.º 10
0
        private FlowComponent getGlobalNavListContainer()
        {
            // This check exists to prevent the display of lookup boxes or other post back controls. With these controls we sometimes don't have a specific
            // destination page to use for an authorization check, meaning that the system code has no way to prevent their display when there is no intermediate
            // user.
            if (ConfigurationStatics.IsIntermediateInstallation && !AppRequestState.Instance.IntermediateUserExists)
            {
                return(null);
            }

            var formItems = EwfUiStatics.AppProvider.GetGlobalNavFormControls()
                            .Select((control, index) => control.GetFormItem(PostBack.GetCompositeId("global", "nav", index.ToString())))
                            .Materialize();
            var listItems = getActionListItems(EwfUiStatics.AppProvider.GetGlobalNavActions()).Concat(formItems.Select(i => i.ToListItem())).Materialize();

            if (!listItems.Any())
            {
                return(null);
            }

            return(new GenericFlowContainer(new LineList(listItems.Select(i => (LineListItem)i)).ToCollection(), classes: globalNavListContainerClass));
        }
        private void addFileRow(
            string postBackIdBase, Func <int, ResourceInfo> thumbnailResourceGetter, IEnumerable <int> openedFileIds, MarkFileAsReadMethod unopenedFileOpenedNotifier,
            EwfTable table, BlobFile file)
        {
            var cells = new List <EwfTableCell>();

            var thumbnailControl = BlobManagementStatics.GetThumbnailControl(file, thumbnailResourceGetter);

            if (thumbnailControl.Any())
            {
                cells.Add(thumbnailControl.ToCell());
            }

            var fileIsUnopened = openedFileIds != null && !openedFileIds.Contains(file.FileId);

            cells.Add(
                new EwfButton(
                    new StandardButtonStyle(file.FileName),
                    behavior: new PostBackBehavior(
                        postBack: PostBack.CreateFull(
                            id: PostBack.GetCompositeId(postBackIdBase, file.FileId.ToString()),
                            firstModificationMethod: () => {
                if (fileIsUnopened)
                {
                    unopenedFileOpenedNotifier?.Invoke(file.FileId);
                }
            },
                            actionGetter: () => new PostBackAction(
                                new PageReloadBehavior(secondaryResponse: new SecondaryResponse(new BlobFileResponse(file.FileId, () => true), false))))))
                .ToCollection()
                .ToCell());

            cells.Add(file.UploadedDate.ToDayMonthYearString(false).ToCell());
            cells.Add((fileIsUnopened ? "New!" : "").ToCell(new TableCellSetup(classes: "ewfNewness".ToCollection())));

            table.AddItem(EwfTableItem.Create(cells, setup: EwfTableItemSetup.Create(id: new SpecifiedValue <int>(file.FileId))));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Returns a JavaScript function call getter that opens a Stripe Checkout modal window. If the window's submit button is clicked, the credit card is
        /// charged or otherwise used. Do not execute the getter before all controls have IDs.
        /// </summary>
        /// <param name="etherealControlParent">The control to which any necessary ethereal controls will be added.</param>
        /// <param name="testPublishableKey">Your test publishable API key. Will be used in non-live installations. Do not pass null.</param>
        /// <param name="livePublishableKey">Your live publishable API key. Will be used in live installations. Do not pass null.</param>
        /// <param name="name">See https://stripe.com/docs/checkout. Do not pass null.</param>
        /// <param name="description">See https://stripe.com/docs/checkout. Do not pass null.</param>
        /// <param name="amountInDollars">See https://stripe.com/docs/checkout, but note that this parameter is in dollars, not cents</param>
        /// <param name="testSecretKey">Your test secret API key. Will be used in non-live installations. Do not pass null.</param>
        /// <param name="liveSecretKey">Your live secret API key. Will be used in live installations. Do not pass null.</param>
        /// <param name="successHandler">A method that executes if the credit-card submission is successful. The first parameter is the charge ID and the second
        /// parameter is the amount of the charge, in dollars.</param>
        /// <param name="prefilledEmailAddressOverride">By default, the email will be prefilled with AppTools.User.Email if AppTools.User is not null. You can
        /// override this with either a specified email address (if user is paying on behalf of someone else) or the empty string (to force the user to type in the
        /// email address).</param>
        public static Func <string> GetCreditCardCollectionJsFunctionCall(
            Control etherealControlParent, string testPublishableKey, string livePublishableKey, string name, string description, decimal?amountInDollars,
            string testSecretKey, string liveSecretKey, Func <string, decimal, StatusMessageAndDestination> successHandler, string prefilledEmailAddressOverride = null)
        {
            if (!EwfApp.Instance.RequestIsSecure(HttpContext.Current.Request))
            {
                throw new ApplicationException("Credit-card collection can only be done from secure pages.");
            }
            EwfPage.Instance.ClientScript.RegisterClientScriptInclude(
                typeof(PaymentProcessingStatics),
                "Stripe Checkout",
                "https://checkout.stripe.com/v2/checkout.js");

            if (amountInDollars.HasValue && amountInDollars.Value.DollarValueHasFractionalCents())
            {
                throw new ApplicationException("Amount must not include fractional cents.");
            }

            ResourceInfo successDestination = null;
            var          postBack           = PostBack.CreateFull(
                id: PostBack.GetCompositeId("ewfCreditCardCollection", description),
                actionGetter: () => new PostBackAction(successDestination));
            var token = new DataValue <string>();

            Func <PostBackValueDictionary, string> tokenHiddenFieldValueGetter;            // unused
            Func <string> tokenHiddenFieldClientIdGetter;

            EwfHiddenField.Create(
                etherealControlParent,
                "",
                postBackValue => token.Value = postBackValue,
                postBack,
                out tokenHiddenFieldValueGetter,
                out tokenHiddenFieldClientIdGetter);

            postBack.AddModificationMethod(
                () => {
                // We can add support later for customer creation, subscriptions, etc. as needs arise.
                if (!amountInDollars.HasValue)
                {
                    throw new ApplicationException("Only simple charges are supported at this time.");
                }

                var apiKey       = ConfigurationStatics.IsLiveInstallation ? liveSecretKey : testSecretKey;
                dynamic response = new StripeClient(apiKey).CreateCharge(
                    amountInDollars.Value,
                    "usd",
                    new CreditCardToken(token.Value),
                    description: description.Any() ? description : null);
                if (response.IsError)
                {
                    if (response.error.type == "card_error")
                    {
                        throw new DataModificationException(response.error.message);
                    }
                    throw new ApplicationException("Stripe error: " + response);
                }

                try {
                    var messageAndDestination = successHandler((string)response.id, amountInDollars.Value);
                    if (messageAndDestination.Message.Any())
                    {
                        EwfPage.AddStatusMessage(StatusMessageType.Info, messageAndDestination.Message);
                    }
                    successDestination = messageAndDestination.Destination;
                }
                catch (Exception e) {
                    throw new ApplicationException("An exception occurred after a credit card was charged.", e);
                }
            });

            EwfPage.Instance.AddPostBack(postBack);
            return(() => {
                var jsTokenHandler = "function( res ) { $( '#" + tokenHiddenFieldClientIdGetter() + "' ).val( res.id ); " +
                                     PostBackButton.GetPostBackScript(postBack, includeReturnFalse: false) + "; }";
                return "StripeCheckout.open( { key: '" + (ConfigurationStatics.IsLiveInstallation ? livePublishableKey : testPublishableKey) + "', name: '" + name +
                "', description: '" + description + "', " + (amountInDollars.HasValue ? "amount: " + amountInDollars.Value * 100 + ", " : "") + "token: " +
                jsTokenHandler + ", email: '" + (prefilledEmailAddressOverride ?? (AppTools.User == null ? "" : AppTools.User.Email)) + "' } )";
            });
        }
        /// <summary>
        /// Creates a modal credit-card collector that is implemented with Stripe Checkout. When the window’s submit button is clicked, the credit card is charged
        /// or otherwise used.
        /// </summary>
        /// <param name="jsOpenStatements">The JavaScript statement list that will open this credit-card collector.</param>
        /// <param name="testPublishableKey">Your test publishable API key. Will be used in non-live installations. Do not pass null.</param>
        /// <param name="livePublishableKey">Your live publishable API key. Will be used in live installations. Do not pass null.</param>
        /// <param name="name">See https://stripe.com/docs/legacy-checkout. Do not pass null.</param>
        /// <param name="description">See https://stripe.com/docs/legacy-checkout. Do not pass null.</param>
        /// <param name="amountInDollars">See https://stripe.com/docs/legacy-checkout, but note that this parameter is in dollars, not cents</param>
        /// <param name="testSecretKey">Your test secret API key. Will be used in non-live installations. Do not pass null.</param>
        /// <param name="liveSecretKey">Your live secret API key. Will be used in live installations. Do not pass null.</param>
        /// <param name="successHandler">A method that executes if the credit-card submission is successful. The first parameter is the charge ID and the second
        /// parameter is the amount of the charge, in dollars.</param>
        /// <param name="prefilledEmailAddressOverride">By default, the email will be prefilled with AppTools.User.Email if AppTools.User is not null. You can
        /// override this with either a specified email address (if user is paying on behalf of someone else) or the empty string (to force the user to type in the
        /// email address).</param>
        public CreditCardCollector(
            JsStatementList jsOpenStatements, string testPublishableKey, string livePublishableKey, string name, string description, decimal?amountInDollars,
            string testSecretKey, string liveSecretKey, Func <string, decimal, StatusMessageAndDestination> successHandler,
            string prefilledEmailAddressOverride = null)
        {
            if (!EwfApp.Instance.RequestIsSecure(HttpContext.Current.Request))
            {
                throw new ApplicationException("Credit-card collection can only be done from secure pages.");
            }

            if (amountInDollars.HasValue && amountInDollars.Value.DollarValueHasFractionalCents())
            {
                throw new ApplicationException("Amount must not include fractional cents.");
            }

            var          token = new DataValue <string>();
            ResourceInfo successDestination = null;
            var          postBack           = PostBack.CreateFull(
                id: PostBack.GetCompositeId("ewfCreditCardCollection", description),
                modificationMethod: () => {
                // We can add support later for customer creation, subscriptions, etc. as needs arise.
                if (!amountInDollars.HasValue)
                {
                    throw new ApplicationException("Only simple charges are supported at this time.");
                }

                StripeCharge response;
                try {
                    response = new StripeGateway(ConfigurationStatics.IsLiveInstallation ? liveSecretKey : testSecretKey).Post(
                        new ChargeStripeCustomer
                    {
                        Amount = (int)(amountInDollars.Value * 100), Currency = "usd", Description = description.Any() ? description : null, Card = token.Value
                    });
                }
                catch (StripeException e) {
                    if (e.Type == "card_error")
                    {
                        throw new DataModificationException(e.Message);
                    }
                    throw new ApplicationException("A credit-card charge failed.", e);
                }

                try {
                    var messageAndDestination = successHandler(response.Id, amountInDollars.Value);
                    if (messageAndDestination.Message.Any())
                    {
                        PageBase.AddStatusMessage(StatusMessageType.Info, messageAndDestination.Message);
                    }
                    successDestination = messageAndDestination.Destination;
                }
                catch (Exception e) {
                    throw new ApplicationException("An exception occurred after a credit card was charged.", e);
                }
            },
                actionGetter: () => new PostBackAction(successDestination));

            var hiddenFieldId = new HiddenFieldId();
            var hiddenFields  = new List <EtherealComponent>();

            FormState.ExecuteWithDataModificationsAndDefaultAction(
                postBack.ToCollection(),
                () => hiddenFields.Add(
                    new EwfHiddenField("", validationMethod: (postBackValue, validator) => token.Value = postBackValue.Value, id: hiddenFieldId).PageComponent));

            FormAction action = new PostBackFormAction(postBack);

            childGetter = () => {
                stripeCheckoutIncludeSetter();
                action.AddToPageIfNecessary();
                jsOpenStatements.AddStatementGetter(
                    () => {
                    var jsTokenHandler = "function( token, args ) { " + hiddenFieldId.GetJsValueModificationStatements("token.id") + " " + action.GetJsStatements() +
                                         " }";
                    return("StripeCheckout.open( { key: '" + (ConfigurationStatics.IsLiveInstallation ? livePublishableKey : testPublishableKey) + "', token: " +
                           jsTokenHandler + ", name: '" + name + "', description: '" + description + "', " +
                           (amountInDollars.HasValue ? "amount: " + amountInDollars.Value * 100 + ", " : "") + "email: '" +
                           (prefilledEmailAddressOverride ?? (AppTools.User == null ? "" : AppTools.User.Email)) + "' } );");
                });
                return(hiddenFields);
            };
        }
        internal HyperlinkBehavior(ResourceInfo destination, bool disableAuthorizationCheck, string target, Func <string, string> actionStatementGetter)
        {
            hasDestination = destination != null;
            userCanNavigateToDestinationPredicate = () => !hasDestination || disableAuthorizationCheck || destination.UserCanAccessResource;

            var destinationAlternativeMode = hasDestination && !disableAuthorizationCheck ? destination.AlternativeMode : null;

            Classes = destinationAlternativeMode is NewContentResourceMode ? ActionComponentCssElementCreator.NewContentClass : ElementClassSet.Empty;

            Url = new Lazy <string>(() => hasDestination ? destination.GetUrl(!disableAuthorizationCheck, false) : "");
            var isPostBackHyperlink = new Lazy <bool>(
                () => hasDestination && !(destinationAlternativeMode is DisabledResourceMode) && !target.Any() && PageBase.Current.IsAutoDataUpdater.Value);

            AttributeGetter = forNonHyperlinkElement =>
                              (hasDestination && !forNonHyperlinkElement ? new ElementAttribute("href", Url.Value).ToCollection() : Enumerable.Empty <ElementAttribute>()).Concat(
                hasDestination && target.Any() && !forNonHyperlinkElement
                                                ? new ElementAttribute("target", target).ToCollection()
                                                : Enumerable.Empty <ElementAttribute>())
                              .Concat(
                // for https://instant.page/
                !isPostBackHyperlink.Value && destination is ResourceBase && !(destinationAlternativeMode is DisabledResourceMode) && !forNonHyperlinkElement
                                                ? new ElementAttribute("data-instant").ToCollection()
                                                : Enumerable.Empty <ElementAttribute>())
                              .Materialize();

            FormAction postBackAction = null;

            string getActionInitStatements(string id, bool omitPreventDefaultStatement, string actionStatements) =>
            "$( '#{0}' ).click( function( e ) {{ {1} }} );".FormatWith(
                id,
                (omitPreventDefaultStatement ? "" : "e.preventDefault();").ConcatenateWithSpace(actionStatements));

            if (destinationAlternativeMode is DisabledResourceMode disabledResourceMode)
            {
                IncludesIdAttribute = forNonHyperlinkElement => true;
                EtherealChildren    = new ToolTip(
                    (disabledResourceMode.Message.Any() ? disabledResourceMode.Message : Translation.ThePageYouRequestedIsDisabled).ToComponents(),
                    out var toolTipInitStatementGetter).ToCollection();
                JsInitStatementGetter = (id, forNonHyperlinkElement) =>
                                        (forNonHyperlinkElement ? "" : getActionInitStatements(id, false, "") + " ") + toolTipInitStatementGetter(id);
            }
            else
            {
                IncludesIdAttribute = forNonHyperlinkElement =>
                                      isPostBackHyperlink.Value || (hasDestination && (actionStatementGetter != null || forNonHyperlinkElement));
                EtherealChildren      = null;
                JsInitStatementGetter = (id, forNonHyperlinkElement) => {
                    var actionStatements = isPostBackHyperlink.Value ? postBackAction.GetJsStatements() :
                                           hasDestination && actionStatementGetter != null?actionStatementGetter(Url.Value) :
                                               hasDestination && forNonHyperlinkElement ? !target.Any()
                                                                                                                  ? "window.location.href = '{0}';".FormatWith(Url.Value)
                                                                                                                  :
                                               target == "_parent"
                                                                                                                          ?
                                               "window.parent.location.href = '{0}';".FormatWith(Url.Value)
                                                                                                                          : "window.open( '{0}', '{1}' );".FormatWith(Url.Value, target) : "";

                    return(actionStatements.Any() ? getActionInitStatements(id, forNonHyperlinkElement, actionStatements) : "");
                };
            }

            IsFocusable = hasDestination;

            PostBackAdder = () => {
                if (!isPostBackHyperlink.Value)
                {
                    return;
                }
                var postBackId = PostBack.GetCompositeId("hyperlink", destination.GetUrl(), disableAuthorizationCheck.ToString());
                postBackAction = new PostBackFormAction(
                    PageBase.Current.GetPostBack(postBackId) ?? PostBack.CreateFull(
                        id: postBackId,
                        actionGetter: () => new PostBackAction(destination, authorizationCheckDisabledPredicate: effectiveDestination => disableAuthorizationCheck)));
                postBackAction.AddToPageIfNecessary();
            };
        }
Exemplo n.º 15
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);
            };
        }