Ejemplo n.º 1
0
        public override IReadOnlyCollection <ActionComponentSetup> GetGlobalNavActions()
        {
            var navButtonSetups = new List <ActionComponentSetup>();

            if (CreateSystem.GetInfo().MatchesCurrent())
            {
                return(navButtonSetups);
            }

            // This will hide itself because Contact Us requires a logged-in user, and this website has no users.
            var contactPage = ContactSupport.GetInfo(PageBase.Current.GetUrl());

            navButtonSetups.Add(new HyperlinkSetup(contactPage, contactPage.ResourceName));

            navButtonSetups.Add(
                new ButtonSetup(
                    "Test",
                    behavior: new MenuButtonBehavior(
                        new EwfButton(
                            new StandardButtonStyle("Test method"),
                            behavior: new PostBackBehavior(
                                postBack: PostBack.CreateFull(
                                    id: "testMethod",
                                    modificationMethod: () => PageBase.AddStatusMessage(StatusMessageType.Info, "Successful method execution.")))).ToCollection())));

            return(navButtonSetups);
        }
Ejemplo n.º 2
0
 private static void addStatusMessageIfClockNotSynchronized(DataValue <string> clientTime)
 {
     if (ClockNotSynchronized(clientTime))
     {
         PageBase.AddStatusMessage(StatusMessageType.Warning, GetClockWrongMessage());
     }
 }
        /// <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();
                PageBase.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"),
                modificationMethod: () => {
                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);
                PageBase.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()));
        }
        /// <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);
            };
        }
Ejemplo n.º 6
0
        GetLogInHiddenFieldsAndMethods()
        {
            var clientTime   = new DataValue <string>();
            var hiddenFields = GetLogInHiddenFieldsAndSetUpClientSideLogic(clientTime);

            return(hiddenFields, ((emailAddress, password, errorMessage) => {
                var errors = new List <string>();

                errorMessage = UserManagementStatics.LocalIdentityProvider.LogInUserWithPassword(
                    emailAddress.Value,
                    password.Value,
                    out var user,
                    errorMessage: errorMessage);
                if (errorMessage.Any())
                {
                    errors.Add(errorMessage);
                }
                else
                {
                    SetFormsAuthCookieAndUser(user, identityProvider: UserManagementStatics.LocalIdentityProvider);
                }

                errors.AddRange(verifyTestCookie());
                addStatusMessageIfClockNotSynchronized(clientTime);

                if (errors.Any())
                {
                    throw new DataModificationException(errors.ToArray());
                }
                return user;
            }, (emailAddress, isPasswordReset, destinationUrl, newUserRoleId) => {
                UserManagementStatics.LocalIdentityProvider.SendLoginCode(
                    emailAddress.Value,
                    isPasswordReset,
                    autoLogInPageUrlGetter,
                    changePasswordPageUrlGetter,
                    destinationUrl,
                    newUserRoleId: newUserRoleId);
                PageBase.AddStatusMessage(StatusMessageType.Info, "Your login code has been sent to {0}.".FormatWith(emailAddress.Value));
            }, (emailAddress, code, errorMessage) => {
                var errors = new List <string>();

                errorMessage = UserManagementStatics.LocalIdentityProvider.LogInUserWithCode(
                    emailAddress,
                    code,
                    out var user,
                    out var destinationUrl,
                    errorMessage: errorMessage);
                if (errorMessage.Any())
                {
                    errors.Add(errorMessage);
                }
                else
                {
                    SetFormsAuthCookieAndUser(user, identityProvider: UserManagementStatics.LocalIdentityProvider);
                }

                errors.AddRange(verifyTestCookie());
                addStatusMessageIfClockNotSynchronized(clientTime);

                if (errors.Any())
                {
                    throw new DataModificationException(errors.ToArray());
                }
                return (user, destinationUrl);
            }, userId => {
                var user = UserManagementStatics.SystemProvider.GetUser(userId);
                SetFormsAuthCookieAndUser(user);

                var errors = new List <string>();
                errors.AddRange(verifyTestCookie());
                addStatusMessageIfClockNotSynchronized(clientTime);
                if (errors.Any())
                {
                    throw new DataModificationException(errors.ToArray());
                }
            }));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a page content object that uses the EWF user interface.
        /// </summary>
        /// <param name="omitContentBox">Pass true to omit the box-style effect around the page content. Useful when all content is contained within multiple
        /// box-style sections.</param>
        /// <param name="pageActions">The page actions.</param>
        /// <param name="contentFootActions">The content-foot actions. The first action, if it is a post-back, will produce a submit button.</param>
        /// <param name="contentFootComponents">The content-foot components.</param>
        /// <param name="dataUpdateModificationMethod">The modification method for the page’s data-update modification.</param>
        /// <param name="isAutoDataUpdater">Pass true to force a post-back when a hyperlink is clicked.</param>
        /// <param name="pageLoadPostBack">A post-back that will be triggered automatically by the browser when the page is finished loading.</param>
        public UiPageContent(
            bool omitContentBox = false, IReadOnlyCollection <ActionComponentSetup> pageActions = null, IReadOnlyCollection <ButtonSetup> contentFootActions = null,
            IReadOnlyCollection <FlowComponent> contentFootComponents = null, Action dataUpdateModificationMethod = null, bool isAutoDataUpdater             = false,
            ActionPostBack pageLoadPostBack = null)
        {
            pageActions = pageActions ?? Enumerable.Empty <ActionComponentSetup>().Materialize();
            if (contentFootActions != null && contentFootComponents != null)
            {
                throw new ApplicationException("Either contentFootActions or contentFootComponents may be specified, but not both.");
            }
            if (contentFootActions == null && contentFootComponents == null)
            {
                contentFootActions = Enumerable.Empty <ButtonSetup>().Materialize();
            }

            entityUiSetup = (PageBase.Current.EsAsBaseType as UiEntitySetup)?.GetUiSetup();
            basicContent  =
                new BasicPageContent(
                    dataUpdateModificationMethod: dataUpdateModificationMethod,
                    isAutoDataUpdater: isAutoDataUpdater,
                    pageLoadPostBack: pageLoadPostBack).Add(
                    getGlobalContainer()
                    .Append(
                        new GenericFlowContainer(
                            getEntityAndTopTabContainer()
                            .Append(
                                EwfTable.Create(style: EwfTableStyle.Raw, classes: sideTabAndContentBlockClass)
                                .AddItem(
                                    EwfTableItem.Create(
                                        (entityUsesTabMode(TabMode.Vertical)
                                                                                                                  ? getSideTabContainer().ToCell(setup: new TableCellSetup(classes: sideTabContainerClass)).ToCollection()
                                                                                                                  : Enumerable.Empty <EwfTableCell>()).Append(
                                            getPageActionListContainer(pageActions)
                                            .Append(
                                                new DisplayableElement(
                                                    context => new DisplayableElementData(
                                                        null,
                                                        () => new DisplayableElementLocalData("div"),
                                                        classes: omitContentBox ? null : contentClass,
                                                        children: content)))
                                            .Concat(getContentFootBlock(isAutoDataUpdater, contentFootActions, contentFootComponents))
                                            .Materialize()
                                            .ToCell(setup: new TableCellSetup(classes: contentClass)))
                                        .Materialize())))
                            .Materialize(),
                            clientSideIdOverride: entityAndTabAndContentBlockId))
                    .Concat(getGlobalFootContainer())
                    .Materialize());

            if (!EwfUiStatics.AppProvider.BrowserWarningDisabled() && AppRequestState.Instance.Browser.IsOldVersionOfMajorBrowser())
            {
                PageBase.AddStatusMessage(
                    StatusMessageType.Warning,
                    StringTools.ConcatenateWithDelimiter(
                        " ",
                        "We've detected that you are not using the latest version of your browser.",
                        "While most features of this site will work, and you will be safe browsing here, we strongly recommend using the newest version of your browser in order to provide a better experience on this site and a safer experience throughout the Internet.") +
                    "<br/>" +
                    Tewl.Tools.NetTools.BuildBasicLink("Click here to get Firefox (it's free)", new ExternalResource("http://www.getfirefox.com").GetUrl(), true) +
                    "<br />" +
                    Tewl.Tools.NetTools.BuildBasicLink(
                        "Click here to get Chrome (it's free)",
                        new ExternalResource("https://www.google.com/intl/en/chrome/browser/").GetUrl(),
                        true) + "<br />" + Tewl.Tools.NetTools.BuildBasicLink(
                        "Click here to get the latest Internet Explorer (it's free)",
                        new ExternalResource("http://www.beautyoftheweb.com/").GetUrl(),
                        true));
            }
        }
        EntityUiSetup UiEntitySetup.GetUiSetup()
        {
            var one = new ModalBoxId();
            var two = new ModalBoxId();

            return(new EntityUiSetup(
                       navActions:
                       new HyperlinkSetup(new ExternalResource("http://www.microsoft.com"), "Go to Microsoft")
                       .Append <ActionComponentSetup>(new ButtonSetup("Custom script", behavior: new CustomButtonBehavior(() => "alert('test');")))
                       .Append(
                           new ButtonSetup(
                               "Menu",
                               behavior: new MenuButtonBehavior(
                                   new StackList(
                                       new EwfHyperlink(new ExternalResource("http://www.apple.com"), new StandardHyperlinkStyle("Apple")).ToComponentListItem()
                                       .Append(
                                           new EwfHyperlink(new ExternalResource("http://www.microsoft.com"), new StandardHyperlinkStyle("Microsoft")).ToComponentListItem())
                                       .Append(new EwfHyperlink(new ExternalResource("http://www.google.com"), new StandardHyperlinkStyle("Google")).ToComponentListItem())
                                       .Append(
                                           new EwfButton(new StandardButtonStyle("Custom script"), behavior: new CustomButtonBehavior(() => "alert('test!');"))
                                           .ToComponentListItem())
                                       .Append(
                                           new EwfButton(
                                               new StandardButtonStyle("Modal"),
                                               behavior: new OpenModalBehavior(
                                                   one,
                                                   etherealChildren: new ModalBox(
                                                       one,
                                                       true,
                                                       new Paragraph("This is a modal box!".ToComponents()).ToCollection()).ToCollection()))
                                           .ToComponentListItem())).ToCollection())))
                       .Append(
                           new ButtonSetup(
                               "Modal Window",
                               behavior: new OpenModalBehavior(
                                   two,
                                   etherealChildren: new ModalBox(
                                       two,
                                       true,
                                       new EwfImage(new ImageSetup("Houses in the mountains"), new ExternalResource("http://r0k.us/graphics/kodak/kodak/kodim08.png"))
                                       .ToCollection()).ToCollection())))
                       .Materialize(),
                       navFormControls:
                       NavFormControl.CreateText(
                           new NavFormControlSetup(100.ToPixels(), "Lookup!"),
                           v => new NavFormControlValidationResult("Lookup '{0}' failed.".FormatWith(v)))
                       .ToCollection(),
                       actions: new ButtonSetup(
                           "Delegate action",
                           behavior: new PostBackBehavior(
                               postBack: PostBack.CreateFull(
                                   id: "delegate",
                                   modificationMethod: () => PageBase.AddStatusMessage(StatusMessageType.Info, "Did Something."))))
                       .Append <ActionComponentSetup>(
                           new HyperlinkSetup(new ExternalResource("http://www.google.com").ToHyperlinkNewTabBehavior(), "Go to Google in new window"))
                       .Append(
                           new ButtonSetup(
                               "Generate error",
                               behavior: new PostBackBehavior(
                                   postBack: PostBack.CreateFull(id: "error", modificationMethod: () => { throw new ApplicationException(); }))))
                       .Materialize(),
                       entitySummaryContent: new Paragraph(
                           "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed quis semper dui. Aenean egestas dolor ac elementum lacinia. Vestibulum eget."
                           .ToComponents()).ToCollection()));
        }