internal static void AddCheckBoxAttributes(WebControl checkBoxElement, Control checkBox, FormValue <bool> checkBoxFormValue,
                                                   FormValue <CommonCheckBox> radioButtonFormValue, string radioButtonListItemId, PostBack postBack, bool autoPostBack,
                                                   IEnumerable <string> onClickJsMethods)
        {
            checkBoxElement.Attributes.Add("type", checkBoxFormValue != null ? "checkbox" : "radio");
            checkBoxElement.Attributes.Add("name", checkBoxFormValue != null ? checkBox.UniqueID : ((FormValue)radioButtonFormValue).GetPostBackValueKey());
            if (radioButtonFormValue != null)
            {
                checkBoxElement.Attributes.Add("value", radioButtonListItemId ?? checkBox.UniqueID);
            }
            if (checkBoxFormValue != null
                                    ? checkBoxFormValue.GetValue(AppRequestState.Instance.EwfPageRequestState.PostBackValues)
                                    : radioButtonFormValue.GetValue(AppRequestState.Instance.EwfPageRequestState.PostBackValues) == checkBox)
            {
                checkBoxElement.Attributes.Add("checked", "checked");
            }

            PostBackButton.EnsureImplicitSubmission(checkBoxElement, postBack);
            var isSelectedRadioButton = radioButtonFormValue != null &&
                                        radioButtonFormValue.GetValue(AppRequestState.Instance.EwfPageRequestState.PostBackValues) == checkBox;
            var postBackScript = autoPostBack && !isSelectedRadioButton
                                                     ? PostBackButton.GetPostBackScript(postBack ?? EwfPage.Instance.DataUpdatePostBack, includeReturnFalse : false)
                                                     : "";

            var customScript = StringTools.ConcatenateWithDelimiter("; ", onClickJsMethods.ToArray());

            checkBoxElement.AddJavaScriptEventScript(JsWritingMethods.onclick, StringTools.ConcatenateWithDelimiter("; ", postBackScript, customScript));
        }
        void ControlTreeDataLoader.LoadData()
        {
            EwfPage.Instance.AddDisplayLink(this);

            if (TagKey == HtmlTextWriterTag.Button)
            {
                PostBackButton.AddButtonAttributes(this);
            }
            this.AddJavaScriptEventScript(JsWritingMethods.onclick, handlerName + "()");
            CssClass    = CssClass.ConcatenateWithSpace("ewfClickable");
            textControl = ActionControlStyle.SetUpControl(this, "");
        }
Beispiel #3
0
        private Box test6(Action <string> setValue)
        {
            var pb  = PostBack.CreateFull(id: "test6");
            var box =
                FormItem.Create(
                    "",
                    new EwfTextBox("", postBack: pb),
                    validationGetter: control => new EwfValidation((pbv, v) => setValue(control.GetPostBackValue(pbv)), pb)).Control;
            var button = new PostBackButton(pb, new ButtonActionControlStyle("OK"), usesSubmitBehavior: false);

            return(new Box(
                       "Post-back with non-default submit button. This post-back-value shouldn't show up when the page's submit button is submitted.",
                       new WebControl[] { box, button }));
        }
 private FormItemBlock(
     bool hideIfEmpty, string heading, bool useFormItemListMode, int?numberOfColumns, int defaultFormItemCellSpan, Unit?firstColumnWidth,
     Unit?secondColumnWidth, TableCellVerticalAlignment verticalAlignment, IEnumerable <FormItem> formItems, PostBackButton button)
 {
     this.hideIfEmpty             = hideIfEmpty;
     this.heading                 = heading;
     this.useFormItemListMode     = useFormItemListMode;
     this.numberOfColumns         = numberOfColumns;
     this.defaultFormItemCellSpan = defaultFormItemCellSpan;
     this.firstColumnWidth        = firstColumnWidth;
     this.secondColumnWidth       = secondColumnWidth;
     this.verticalAlignment       = verticalAlignment;
     this.formItems               = (formItems ?? new FormItem[0]).ToList();
     this.button = button;
 }
        void ControlTreeDataLoader.LoadData()
        {
            if (hideIfEmpty && !formItems.Any())
            {
                Visible = false;
                return;
            }

            CssClass = CssClass.ConcatenateWithSpace(CssElementCreator.CssClass);

            var theButton = button;

#pragma warning disable 618 // Disables obsolete warning
            if (IncludeButtonWithThisText != null)
            {
                theButton = new PostBackButton(EwfPage.Instance.DataUpdatePostBack, new ButtonActionControlStyle(IncludeButtonWithThisText));
            }
#pragma warning restore 618
            if (theButton != null)
            {
                theButton.ActionControlStyle = new ButtonActionControlStyle(theButton.ActionControlStyle.Text);
                theButton.Width = Unit.Percentage(50);

                // We need to do logic to get the button to be on the right of the row.
                if (useFormItemListMode && numberOfColumns.HasValue)
                {
                    var widthOfLastRowWithButton     = getFormItemRows(formItems, numberOfColumns.Value).Last().Sum(fi => getCellSpan(fi)) + defaultFormItemCellSpan;
                    var numberOfPlaceholdersRequired = 0;
                    if (widthOfLastRowWithButton < numberOfColumns.Value)
                    {
                        numberOfPlaceholdersRequired = numberOfColumns.Value - widthOfLastRowWithButton;
                    }
                    if (widthOfLastRowWithButton > numberOfColumns.Value)
                    {
                        numberOfPlaceholdersRequired = numberOfColumns.Value - ((widthOfLastRowWithButton - numberOfColumns.Value) % numberOfColumns.Value);
                    }

                    numberOfPlaceholdersRequired.Times(() => formItems.Add(getPlaceholderFormItem()));
                }
                formItems.Add(
                    FormItem.Create(
                        "",
                        theButton,
                        textAlignment: TextAlignment.Right,
                        cellSpan: defaultFormItemCellSpan));
            }
            Controls.Add(useFormItemListMode ? getTableForFormItemList() : getTableForFormItemTable());
        }
        private Section test6(Action <string> setValue)
        {
            var pb = PostBack.CreateFull(id: "test6");

            return(FormState.ExecuteWithDataModificationsAndDefaultAction(
                       pb.ToCollection(),
                       () => {
                var box =
                    FormItem.Create("", new EwfTextBox(""), validationGetter: control => new EwfValidation((pbv, v) => setValue(control.GetPostBackValue(pbv))))
                    .Control;
                var button = new PostBackButton(new ButtonActionControlStyle("OK"), usesSubmitBehavior: false);
                return new Section(
                    "Post-back with non-default submit button. This post-back-value shouldn't show up when the page's submit button is submitted.",
                    new WebControl[] { box, button },
                    style: SectionStyle.Box);
            }));
        }
Beispiel #7
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 block with a classic "label on the left, value on the right" layout.
 /// Button, if passed, should be a PostBackButton with a control style containing text, but the control style will be overridden with ButtonActionControlStyle.
 /// By creating the button, you have control over its post back object and whether it uses submit behavior.
 /// </summary>
 public static FormItemBlock CreateFormItemTable(
     bool hideIfEmpty = false, string heading = "", Unit?firstColumnWidth = null, Unit?secondColumnWidth = null, IEnumerable <FormItem> formItems = null, PostBackButton button = null)
 {
     return(new FormItemBlock(hideIfEmpty, heading, false, null, 1, firstColumnWidth, secondColumnWidth, TableCellVerticalAlignment.NotSpecified, formItems, button));
 }
 /// <summary>
 /// Creates a block with the given number of columns where each form item control's label is placed directly on top of it. NumberOfColumns defaults to the
 /// sum of the cellspans of the given form items.
 /// Button, if passed, should be a PostBackButton with a control style containing text, but the control style will be overridden with ButtonActionControlStyle.
 /// By creating the button, you have control over its post back object and whether it uses submit behavior.
 /// </summary>
 // While this method shares numberOfColumns semantics with ControlList, it is fundamentally different because instead of dealing with plain old controls,
 // this method deals with form items, which can span multiple cells. ControlList is designed to represent simple ordered and unordered lists and should
 // never support cell spanning.
 public static FormItemBlock CreateFormItemList(
     bool hideIfEmpty = false, string heading = "", int?numberOfColumns = null, int defaultFormItemCellSpan = 1,
     TableCellVerticalAlignment verticalAlignment = TableCellVerticalAlignment.Bottom, IEnumerable <FormItem> formItems = null, PostBackButton button = null)
 {
     return(new FormItemBlock(hideIfEmpty, heading, true, numberOfColumns, defaultFormItemCellSpan, null, null, verticalAlignment, formItems, button));
 }