Esempio n. 1
0
        /// <summary>
        /// Creates a submit button.
        /// </summary>
        /// <param name="style">The style.</param>
        /// <param name="displaySetup"></param>
        /// <param name="classes">The classes on the button.</param>
        /// <param name="postBack">Pass null to use the post-back corresponding to the first of the current data modifications.</param>
        public SubmitButton(ButtonStyle style, DisplaySetup displaySetup = null, ElementClassSet classes = null, PostBack postBack = null)
        {
            var elementChildren = style.GetChildren();
            var postBackAction  = new PostBackFormAction(postBack ?? FormState.Current.PostBack);

            children = new DisplayableElement(
                context => {
                FormAction action = postBackAction;
                action.AddToPageIfNecessary();

                if (EwfPage.Instance.SubmitButtonPostBack != null)
                {
                    throw new ApplicationException("A submit button already exists on the page.");
                }
                EwfPage.Instance.SubmitButtonPostBack = postBackAction.PostBack;

                return(new DisplayableElementData(
                           displaySetup,
                           () =>
                           new DisplayableElementLocalData(
                               "button",
                               attributes: new[] { Tuple.Create("name", EwfPage.ButtonElementName), Tuple.Create("value", "v") },
                               jsInitStatements: style.GetJsInitStatements(context.Id)),
                           classes: style.GetClasses().Add(classes ?? ElementClassSet.Empty),
                           children: elementChildren));
            }).ToCollection();
        }
Esempio n. 2
0
        /// <summary>
        /// Creates a submit button.
        /// </summary>
        /// <param name="style">The style.</param>
        /// <param name="displaySetup"></param>
        /// <param name="classes">The classes on the button.</param>
        /// <param name="postBack">Pass null to use the post-back corresponding to the first of the current data modifications.</param>
        public SubmitButton(ButtonStyle style, DisplaySetup displaySetup = null, ElementClassSet classes = null, PostBack postBack = null)
        {
            var elementChildren = style.GetChildren();
            var postBackAction  = new PostBackFormAction(postBack ?? FormState.Current.PostBack);

            children = new DisplayableElement(
                context => {
                FormAction action = postBackAction;
                action.AddToPageIfNecessary();

                if (PageBase.Current.SubmitButtonPostBack != null)
                {
                    throw new ApplicationException("A submit button already exists on the page.");
                }
                PageBase.Current.SubmitButtonPostBack = postBackAction.PostBack;

                return(new DisplayableElementData(
                           displaySetup,
                           () => new DisplayableElementLocalData(
                               "button",
                               new FocusabilityCondition(true),
                               isFocused => {
                    var attributes =
                        new List <ElementAttribute> {
                        new ElementAttribute("name", PageBase.ButtonElementName), new ElementAttribute("value", "v")
                    };
                    if (isFocused)
                    {
                        attributes.Add(new ElementAttribute("autofocus"));
                    }

                    return new DisplayableElementFocusDependentData(attributes: attributes, jsInitStatements: style.GetJsInitStatements(context.Id));
                }),
                           classes: style.GetClasses().Add(classes ?? ElementClassSet.Empty),
                           children: elementChildren));
            }).ToCollection();
        }
        /// <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);
            };
        }
Esempio n. 4
0
 /// <summary>
 /// Creates a post-back behavior.
 /// </summary>
 /// <param name="postBack">Pass null to use the post-back corresponding to the first of the current data modifications.</param>
 public PostBackBehavior(PostBack postBack = null)
 {
     PostBackAction = new PostBackFormAction(postBack ?? FormState.Current.PostBack);
 }
        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();
            };
        }