internal ModalWindow( Control parent, Control content, string title = "", PostBack postBack = null, bool open = false )
        {
            control = new Block( new Section( title, content.ToSingleElementArray().Concat( getButtonTable( postBack ) ) ) ) { CssClass = CssElementCreator.CssClass };
            this.open = open;

            EwfPage.Instance.AddEtherealControl( parent, this );
        }
        internal void SetUpClickableControl( WebControl clickableControl )
        {
            if( resource == null && postBack == null && script == "" )
                return;

            clickableControl.CssClass = clickableControl.CssClass.ConcatenateWithSpace( "ewfClickable" );

            if( resource != null && EwfPage.Instance.IsAutoDataUpdater ) {
                postBack = EwfLink.GetLinkPostBack( resource );
                resource = null;
            }

            Func<string> scriptGetter;
            if( resource != null )
                scriptGetter = () => "location.href = '" + EwfPage.Instance.GetClientUrl( resource.GetUrl() ) + "'; return false";
            else if( postBack != null ) {
                EwfPage.Instance.AddPostBack( postBack );
                scriptGetter = () => PostBackButton.GetPostBackScript( postBack );
            }
            else
                scriptGetter = () => script;

            // Defer script generation until after all controls have IDs.
            EwfPage.Instance.PreRender += delegate { clickableControl.AddJavaScriptEventScript( JsWritingMethods.onclick, scriptGetter() ); };
        }
Пример #3
0
        internal ModalWindow(Control content, string title = "", PostBack postBack = null)
        {
            control = new Block(content)
            {
                CssClass = CssElementCreator.CssClass
            };
            this.title    = title;
            this.postBack = postBack;

            EwfPage.Instance.AddEtherealControl(this);
        }
        // NOTE: EVERYTHING should be done here. We shouldn't have LoadData. We should audit everyone using this control and see if we can improve things.
        // NOTE: This should also be full of delegates that run when events (such as deleting a file) are occurring.
        // NOTE: There should be a way to tell if a file was uploaded.
        void ControlTreeDataLoader.LoadData()
        {
            if (fileCollectionId != null)
            {
                file = BlobFileOps.GetFirstFileFromCollection(fileCollectionId.Value);
            }

            var controlStack = ControlStack.Create(true);

            if (file != null)
            {
                var download = new PostBackButton(
                    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 SecondaryResponse(new BlobFileResponse(BlobFileOps.GetFirstFileFromCollection(fileCollectionId.Value).FileId, () => true), false)));
                }),
                    new TextActionControlStyle(Translation.DownloadExisting + " (" + file.FileName + ")"),
                    false);
                controlStack.AddControls(download);
            }
            else if (!HideNoExistingFileMessage)
            {
                controlStack.AddControls(new Label {
                    Text = Translation.NoExistingFile
                });
            }

            uploadedFile = new EwfFileUpload();
            if (file != null)
            {
                uploadedFile.SetInitialDisplay(false);
                var replaceExistingFileLink = new ToggleButton(
                    uploadedFile.ToSingleElementArray(),
                    new TextActionControlStyle(Translation.ClickHereToReplaceExistingFile))
                {
                    AlternateText = ""
                };
                controlStack.AddControls(replaceExistingFileLink);
            }

            controlStack.AddControls(uploadedFile);

            var thumbnailControl = BlobFileOps.GetThumbnailControl(file, ThumbnailResourceInfoCreator);

            if (thumbnailControl != null)
            {
                Controls.Add(thumbnailControl);
            }
            Controls.Add(controlStack);
        }
        protected override PageContent getContent()
        {
            var content = new UiPageContent(omitContentBox: true);

            if (UserManagementStatics.IdentityProviders.OfType <SamlIdentityProvider>().Any())
            {
                var certificate = UserManagementStatics.GetCertificate();
                content.Add(
                    new Section(
                        "Identity providers",
                        FormItemList.CreateStack(
                            items:
                            (certificate.Any()
                                                                          ? "Certificate valid until {0}.".FormatWith(
                                 new X509Certificate2(Convert.FromBase64String(certificate), UserManagementStatics.CertificatePassword).NotAfter
                                 .ToDayMonthYearString(
                                     false))
                             .ToComponents()
                                                                          : "No certificate.".ToComponents()).Concat(" ".ToComponents())
                            .Append(
                                new EwfButton(
                                    new StandardButtonStyle("Regenerate", buttonSize: ButtonSize.ShrinkWrap),
                                    behavior: new ConfirmationButtonBehavior(
                                        "Are you sure?".ToComponents(),
                                        postBack: PostBack.CreateFull(
                                            "certificate",
                                            modificationMethod: () => UserManagementStatics.UpdateCertificate(generateCertificate(DateTimeOffset.UtcNow))))))
                            .Materialize()
                            .ToFormItem(label: "System self-signed certificate".ToComponents())
                            .Concat(
                                AuthenticationStatics.SamlIdentityProviders.Any()
                                                                                ? new EwfHyperlink(EnterpriseWebFramework.UserManagement.SamlResources.Metadata.GetInfo(), new StandardHyperlinkStyle(""))
                                .ToFormItem(label: "Application SAML metadata".ToComponents())
                                .ToCollection()
                                                                                : Enumerable.Empty <FormItem>())
                            .Materialize())
                        .ToCollection(),
                        style: SectionStyle.Box));
            }
            content.Add(
                new Section(
                    "System users",
                    EwfTable.Create(
                        tableActions: new HyperlinkSetup(new SystemUser(Es, null), "Create User").ToCollection(),
                        headItems: EwfTableItem.Create("Email".ToCell().Append("Role".ToCell()).Materialize()).ToCollection())
                    .AddData(
                        UserManagementStatics.SystemProvider.GetUsers(),
                        user => EwfTableItem.Create(
                            user.Email.ToCell().Append(user.Role.Name.ToCell()).Materialize(),
                            setup: EwfTableItemSetup.Create(activationBehavior: ElementActivationBehavior.CreateHyperlink(new SystemUser(Es, user.UserId)))))
                    .ToCollection(),
                    style: SectionStyle.Box));
            return(content);
        }
        protected override void loadData()
        {
            HtmlBlockEditorModification mod;

            FormState.ExecuteWithDataModificationsAndDefaultAction(
                PostBack.CreateFull().ToCollection(),
                () => {
                ph.AddControlsReturnThis(new HtmlBlockEditor(null, id => { }, out mod).ToFormItem("").ToControl());
                EwfUiStatics.SetContentFootActions(new ActionButtonSetup("Post Back", new PostBackButton()));
            });
        }
Пример #7
0
        private IReadOnlyCollection <PhrasingComponent> getFavoriteTabComponents()
        {
            const string label = "Favorited Articles";

            return(ShowFavorites
                                       ? label.ToComponents()
                                       : new EwfButton(
                       new StandardButtonStyle(label),
                       behavior: new PostBackBehavior(
                           postBack: PostBack.CreateFull(id: "favorite", modificationMethod: () => parametersModification.ShowFavorites = true))).ToCollection());
        }
 protected override void loadData()
 {
     FormState.ExecuteWithDataModificationsAndDefaultAction(
         PostBack.CreateFull().ToCollection(),
         () => {
         ph.AddControlsReturnThis(
             new HtmlBlockEditor(null, id => {}, out var mod).ToFormItem(label: Enumerable.Empty <PhrasingComponent>().Materialize())
             .ToComponentCollection()
             .GetControls());
         EwfUiStatics.SetContentFootActions(new ButtonSetup("Post Back").ToCollection());
     });
 }
Пример #9
0
        public BlobFileManager(int?fileCollectionId)
        {
            this.fileCollectionId = fileCollectionId;

            if (fileCollectionId != null)
            {
                file = BlobFileOps.GetFirstFileFromCollection(fileCollectionId.Value);
            }

            var controlStack = ControlStack.Create(true);

            if (file != null)
            {
                var download = new PostBackButton(
                    new TextActionControlStyle(Translation.DownloadExisting + " (" + file.FileName + ")"),
                    usesSubmitBehavior: false,
                    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 SecondaryResponse(new BlobFileResponse(BlobFileOps.GetFirstFileFromCollection(fileCollectionId.Value).FileId, () => true), false)));
                }));
                controlStack.AddControls(download);
            }
            else if (!HideNoExistingFileMessage)
            {
                controlStack.AddControls(new Label {
                    Text = Translation.NoExistingFile
                });
            }

            uploadedFile = new EwfFileUpload();
            if (file != null)
            {
                uploadedFile.SetInitialDisplay(false);
                var replaceExistingFileLink = new ToggleButton(
                    uploadedFile.ToCollection(),
                    new TextActionControlStyle(Translation.ClickHereToReplaceExistingFile),
                    false,
                    (postBackValue, validator) => { })
                {
                    AlternateText = ""
                };
                controlStack.AddControls(replaceExistingFileLink);
            }

            controlStack.AddControls(uploadedFile);

            this.AddControlsReturnThis(BlobFileOps.GetThumbnailControl(file, ThumbnailResourceInfoCreator));
            Controls.Add(controlStack);
        }
        private void addFileRow(DynamicTable table, BlobFile file, ActionPostBack deletePb, List <Func <bool> > deleteModMethods)
        {
            var cells = new List <EwfTableCell>();

            var thumbnailControl = BlobFileOps.GetThumbnailControl(file, ThumbnailResourceInfoCreator);

            if (thumbnailControl != null)
            {
                cells.Add(thumbnailControl);
            }

            var fileIsUnread = fileIdsMarkedAsRead != null && !fileIdsMarkedAsRead.Contains(file.FileId);

            cells.Add(
                new PostBackButton(
                    PostBack.CreateFull(
                        id: PostBack.GetCompositeId(postBackIdBase, file.FileId.ToString()),
                        firstModificationMethod: () => {
                if (fileIsUnread && markFileAsReadMethod != null)
                {
                    markFileAsReadMethod(file.FileId);
                }
            },
                        actionGetter: () => new PostBackAction(new SecondaryResponse(new BlobFileResponse(file.FileId, () => true), false))),
                    new TextActionControlStyle(file.FileName),
                    false)
            {
                ToolTip = file.FileName
            });

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

            var delete         = false;
            var deleteCheckBox =
                FormItem.Create(
                    "",
                    new EwfCheckBox(false, postBack: deletePb),
                    validationGetter: control => new EwfValidation((pbv, v) => { delete = control.IsCheckedInPostBack(pbv); }, deletePb)).ToControl();

            cells.Add(ReadOnly ? null : deleteCheckBox);
            deleteModMethods.Add(
                () => {
                if (!delete)
                {
                    return(false);
                }
                BlobFileOps.SystemProvider.DeleteFile(file.FileId);
                return(true);
            });

            table.AddRow(cells.ToArray());
        }
Пример #11
0
 protected override PageContent getContent() =>
 new UiPageContent().Add(
     new StackList(
         new EwfButton(
             new StandardButtonStyle("Send Health Check"),
             behavior: new PostBackBehavior(
                 postBack: PostBack.CreateFull(id: "sendHealthCheck", modificationMethod: () => EwfApp.Instance.SendHealthCheck()))).ToComponentListItem()
         .Append(
             new EwfButton(
                 new StandardButtonStyle("Throw Unhandled Exception"),
                 behavior: new PostBackBehavior(postBack: PostBack.CreateFull(id: "throwException", modificationMethod: throwException)))
             .ToComponentListItem())));
Пример #12
0
        protected override void loadData()
        {
            BasicPage.Instance.Body.Attributes["class"] = CssElementCreator.SelectUserPageBodyCssClass;

            ph.AddControlsReturnThis(new PageName());

            if (AppTools.IsLiveInstallation)
            {
                ph.AddControlsReturnThis(
                    new Paragraph(
                        new Strong("Warning:"),
                        " Do not impersonate a user without permission. Your actions will be attributed to the user you are impersonating, not to you.".GetLiteralControl()));
            }

            var pb = PostBack.CreateFull(
                actionGetter: () => new PostBackAction(new ExternalResourceInfo(info.ReturnUrl.Any() ? info.ReturnUrl : NetTools.HomeUrl)));

            DataValue <User> user = new DataValue <User>();

            ph.AddControlsReturnThis(
                FormItem.Create(
                    "User's email address (leave blank for anonymous)",
                    new EwfTextBox(""),
                    validationGetter: control => new EwfValidation(
                        (pbv, validator) => {
                var errorHandler = new ValidationErrorHandler("user");
                var emailAddress = validator.GetEmailAddress(errorHandler, control.GetPostBackValue(pbv), true);
                if (errorHandler.LastResult != ErrorCondition.NoError)
                {
                    return;
                }
                if (!emailAddress.Any())
                {
                    user.Value = null;
                    return;
                }
                user.Value = UserManagementStatics.GetUser(emailAddress);
                if (user.Value == null)
                {
                    validator.NoteErrorAndAddMessage("The email address you entered does not match a user.");
                }
            },
                        pb)).ToControl(),
                new Paragraph(
                    new PostBackButton(
                        pb,
                        new ButtonActionControlStyle(
                            AppRequestState.Instance.ImpersonatorExists ? "Change User" : "Begin Impersonation",
                            buttonSize: ButtonActionControlStyle.ButtonSize.Large))));

            pb.AddModificationMethod(() => UserImpersonationStatics.BeginImpersonation(user.Value));
        }
Пример #13
0
        protected override PageContent getContent()
        {
            var mod    = getMod();
            var tagIds = ComponentStateItem.Create(
                "tags",
                ArticleId.HasValue
                                        ? ArticleTagsTableRetrieval.GetRowsLinkedToArticle(ArticleId.Value).Select(i => i.TagId).Materialize()
                                        : Enumerable.Empty <int>().Materialize(),
                v => v.All(id => TagsTableRetrieval.GetRowMatchingId(id, returnNullIfNoMatch: true) != null),
                true);

            return(FormState.ExecuteWithDataModificationsAndDefaultAction(
                       PostBack.CreateFull(
                           modificationMethod: () => {
                if (!ArticleId.HasValue)
                {
                    mod.ArticleId = MainSequence.GetNextValue();
                    mod.Slug = getSuffixedSlug(mod.Title.ToUrlSlug());
                    mod.CreationDateAndTime = DateTime.UtcNow;
                }
                mod.Execute();

                if (ArticleId.HasValue)
                {
                    ArticleTagsModification.DeleteRows(new ArticleTagsTableEqualityConditions.ArticleId(ArticleId.Value));
                }
                foreach (var i in tagIds.Value.Value)
                {
                    ArticleTagsModification.InsertRow(mod.ArticleId, i);
                }
            },
                           actionGetter: () => new PostBackAction(Article.GetInfo(mod.ArticleId)))
                       .ToCollection(),
                       () => {
                var stack = FormItemList.CreateStack(generalSetup: new FormItemListSetup(etherealContent: tagIds.ToCollection()));

                stack.AddItems(
                    mod.GetTitleTextControlFormItem(false, label: "Article title".ToComponents(), value: ArticleId.HasValue ? null : "")
                    .Append(
                        mod.GetDescriptionTextControlFormItem(false, label: "What's this article about?".ToComponents(), value: ArticleId.HasValue ? null : ""))
                    .Append(
                        mod.GetBodyMarkdownTextControlFormItem(
                            false,
                            label: "Write your article (in markdown)".ToComponents(),
                            controlSetup: TextControlSetup.Create(numberOfRows: 8),
                            value: ArticleId.HasValue ? null : ""))
                    .Append(getTagFormItem(tagIds.Value))
                    .Materialize());

                return new UiPageContent(contentFootActions: new ButtonSetup("Publish Article").ToCollection()).Add(stack);
            }));
        }
 protected override PageContent getContent() =>
 new UiPageContent().Add(
     FormState.ExecuteWithDataModificationsAndDefaultAction(
         PostBack.CreateFull().ToCollection(),
         () => FormItemList.CreateStack(
             generalSetup: new FormItemListSetup(buttonSetup: new ButtonSetup("Submit")),
             items: getControls().Select((getter, i) => getter((i + 1).ToString())).Materialize()))
     .Append <FlowComponent>(
         new Section(
             "Independent Controls",
             FormItemList.CreateStack(items: getIndependentControls().Select((getter, i) => getter("I-" + (i + 1).ToString())).Materialize())
             .ToCollection()))
     .Materialize());
        private Section test5(Action <string> setValue)
        {
            var pb = PostBack.CreateFull(id: "test5");

            return(FormState.ExecuteWithDataModificationsAndDefaultAction(
                       pb.ToCollection(),
                       () => {
                var box =
                    FormItem.Create("", new EwfTextBox(""), validationGetter: control => new EwfValidation((pbv, v) => setValue(control.GetPostBackValue(pbv))))
                    .Control;
                return new Section("Post-back on enter.", box.ToCollection(), style: SectionStyle.Box);
            }));
        }
Пример #16
0
        private IReadOnlyCollection <PhrasingComponent> getGlobalTabComponents(DataValue <string> filter, UpdateRegionSet resultUpdateRegions)
        {
            const string label = "Global Feed";

            return(filter.Value != "user" && !filter.Value.StartsWith("tag")
                                       ? label.ToComponents()
                                       : new EwfButton(
                       new StandardButtonStyle(label),
                       behavior: new PostBackBehavior(
                           postBack: PostBack.CreateIntermediate(
                               resultUpdateRegions.ToCollection(),
                               id: "global",
                               modificationMethod: () => filter.Value = "global"))).ToCollection());
        }
        private IEnumerable<Control> getButtonTable( PostBack postBack )
        {
            if( postBack == null )
                return new Control[ 0 ];

            var table = EwfTable.Create( style: EwfTableStyle.StandardLayoutOnly );
            table.AddItem(
                new EwfTableItem(
                    new ControlLine(
                        new CustomButton( () => "$.modal.close()" ) { ActionControlStyle = new ButtonActionControlStyle( "Cancel" ) },
                        new PostBackButton( postBack, new ButtonActionControlStyle( "Continue" ), usesSubmitBehavior: false ) ).ToCell(
                            new TableCellSetup( textAlignment: TextAlignment.Right ) ) ) );
            return table.ToSingleElementArray();
        }
 IReadOnlyCollection <ActionComponentSetup> UiEntitySetupBase.GetActions() =>
 new ButtonSetup(
     "Delegate action",
     behavior: new PostBackBehavior(
         postBack: PostBack.CreateFull(
             id: "delegate",
             firstModificationMethod: () => EwfPage.AddStatusMessage(StatusMessageType.Info, "Did Something.")))).ToCollection <ActionComponentSetup>()
 .Append(new HyperlinkSetup(new ExternalResourceInfo("http://www.google.com").ToHyperlinkNewTabBehavior(), "Go to Google in new window"))
 .Append(
     new ButtonSetup(
         "Generate error",
         behavior: new PostBackBehavior(
             postBack: PostBack.CreateFull(id: "error", firstModificationMethod: () => { throw new ApplicationException(); }))))
 .Materialize();
Пример #19
0
 protected override void loadData()
 {
     ph.AddControlsReturnThis(
         ControlStack.CreateWithControls(
             true,
             new PostBackButton(
                 PostBack.CreateFull(id: "sendHealthCheck", firstModificationMethod: () => EwfApp.Instance.SendHealthCheck()),
                 new ButtonActionControlStyle("Send Health Check"),
                 usesSubmitBehavior: false),
             new PostBackButton(
                 PostBack.CreateFull(id: "throwException", firstModificationMethod: throwException),
                 new ButtonActionControlStyle("Throw Unhandled Exception"),
                 usesSubmitBehavior: false)));
 }
Пример #20
0
        internal static string GetPostBackScript(PostBack postBack, bool includeReturnFalse = true)
        {
            if (EwfPage.Instance.GetPostBack(postBack.Id) != postBack)
            {
                throw new ApplicationException("The post-back must have been added to the page.");
            }
            var validationPostBack = postBack is ActionPostBack ? ((ActionPostBack)postBack).ValidationDm as PostBack : null;

            if (validationPostBack != null && EwfPage.Instance.GetPostBack(validationPostBack.Id) != validationPostBack)
            {
                throw new ApplicationException("The post-back's validation data-modification, if it is a post-back, must have been added to the page.");
            }
            return("postBack( '{0}' )".FormatWith(postBack.Id) + (includeReturnFalse ? "; return false" : ""));
        }
Пример #21
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 }));
        }
Пример #22
0
 private IReadOnlyCollection <PhrasingComponent> getTagListComponents(DataValue <IReadOnlyCollection <int> > tagIds, UpdateRegionSet removeUpdateRegions) =>
 tagIds.Value.Select(
     tagId => new GenericPhrasingContainer(
         new EwfButton(
             new CustomButtonStyle(children: new FontAwesomeIcon("fa-times").ToCollection()),
             behavior: new PostBackBehavior(
                 postBack: PostBack.CreateIntermediate(
                     removeUpdateRegions.ToCollection(),
                     id: PostBack.GetCompositeId("removeTag", tagId.ToString()),
                     modificationMethod: () => tagIds.Value = tagIds.Value.Where(i => i != tagId).Materialize())))
         .Concat(" {0}".FormatWith(TagsTableRetrieval.GetRowMatchingId(tagId).TagName).ToComponents())
         .Materialize(),
         classes: ElementClasses.EditorTag))
 .Materialize();
Пример #23
0
        protected override PageContent getContent()
        {
            var mod      = getMod();
            var password = new DataValue <string> {
                Value = ""
            };
            Tuple <IReadOnlyCollection <EtherealComponent>, Action <int> > logInHiddenFieldsAndMethod = null;

            return(FormState.ExecuteWithDataModificationsAndDefaultAction(
                       PostBack.CreateFull(
                           modificationMethod: () => {
                if (AppTools.User == null)
                {
                    mod.UserId = MainSequence.GetNextValue();
                }
                if (password.Value.Any())
                {
                    var passwordSalter = new Password(password.Value);
                    mod.Salt = passwordSalter.Salt;
                    mod.SaltedPassword = passwordSalter.ComputeSaltedHash();
                }
                mod.Execute();

                logInHiddenFieldsAndMethod?.Item2(mod.UserId);
            },
                           actionGetter: () => new PostBackAction(logInHiddenFieldsAndMethod != null ? (PageBase)Home.GetInfo() : Profile.GetInfo(AppTools.User.UserId)))
                       .ToCollection(),
                       () => {
                var content = new UiPageContent(contentFootActions: new ButtonSetup(AppTools.User != null ? "Update Settings" : "Sign up").ToCollection());

                if (AppTools.User == null)
                {
                    content.Add(
                        new EwfHyperlink(
                            EnterpriseWebLibrary.EnterpriseWebFramework.UserManagement.Pages.LogIn.GetInfo(Home.GetInfo().GetUrl()),
                            new StandardHyperlinkStyle("Have an account?")));
                }

                content.Add(getFormItemStack(mod, password));

                if (AppTools.User == null)
                {
                    logInHiddenFieldsAndMethod = FormsAuthStatics.GetLogInHiddenFieldsAndSpecifiedUserLogInMethod();
                    content.Add(logInHiddenFieldsAndMethod.Item1);
                }

                return content;
            }));
        }
        private ControlListItem getIdItem(int id)
        {
            var rs = new UpdateRegionSet();
            var pb = PostBack.CreateIntermediate(rs.ToSingleElementArray(), DataUpdate, id: PostBack.GetCompositeId("id", id.ToString()));

            var itemStack = ControlStack.Create(true);

            itemStack.AddControls(new EwfTextBox("ID {0}".FormatWith(id)));
            itemStack.AddControls(
                new PostBackButton(pb, new ButtonActionControlStyle("Remove", buttonSize: ButtonActionControlStyle.ButtonSize.ShrinkWrap), usesSubmitBehavior: false));

            pb.AddModificationMethod(() => parametersModification.ItemIds = parametersModification.ItemIds.Where(i => i != id).ToArray());

            return(new ControlListItem(itemStack.ToSingleElementArray(), id.ToString(), removalUpdateRegionSet: rs));
        }
        protected override void loadData()
        {
            var pb = PostBack.CreateFull();

            FormState.ExecuteWithDataModificationsAndDefaultAction(
                pb.ToCollection(),
                () => {
                ph.AddControlsReturnThis(
                    FormItemBlock.CreateFormItemTable(heading: "Radio Button List, Vertical", formItems: getRadioItems(false)),
                    FormItemBlock.CreateFormItemTable(heading: "Radio Button List, Horizontal", formItems: getRadioItems(true)),
                    getSelect2UpgradeTestingInfo(),
                    FormItemBlock.CreateFormItemTable(heading: "Drop-Down List", formItems: getDropDownItems()));
            });
            EwfUiStatics.SetContentFootActions(new ActionButtonSetup("Submit", new PostBackButton(pb)));
        }
Пример #26
0
        private IReadOnlyCollection <PhrasingComponent> getUserTabComponents(DataValue <string> filter, UpdateRegionSet resultUpdateRegions)
        {
            const string label = "Your Feed";

            return(AppTools.User != null
                                       ? filter.Value == "user" ? label.ToComponents() :
                   new EwfButton(
                       new StandardButtonStyle(label),
                       behavior: new PostBackBehavior(
                           postBack: PostBack.CreateIntermediate(
                               resultUpdateRegions.ToCollection(),
                               id: "user",
                               modificationMethod: () => filter.Value = "user"))).ToCollection()
                                       : Enumerable.Empty <PhrasingComponent>().Materialize());
        }
Пример #27
0
        private Box test2(Action <string> setValue)
        {
            var pb  = PostBack.CreateFull(id: "test2");
            var box =
                FormItem.Create(
                    "",
                    new EwfTextBox("", postBack: pb),
                    validationGetter: control => new EwfValidation((pbv, v) => setValue(control.GetPostBackValue(pbv)), pb)).Control;

            box.SetupAutoComplete(TestService.GetInfo(), AutoCompleteOption.PostBackOnItemSelect);
            return
                (new Box(
                     "Autofill behavior. Typing more than 3 characters should bring up autofill options from a web service. " + "Selecting an item will cause a post-back.",
                     box.ToSingleElementArray()));
        }
        protected override void loadData()
        {
            var pb = PostBack.CreateFull();

            FormState.ExecuteWithDataModificationsAndDefaultAction(
                pb.ToCollection(),
                () => {
                addMessageIfNotNull(ph, getTest1(null));
                ph.AddControlsReturnThis(test1(setTest1));

                addMessageIfNotNull(ph, getTest2(null));
                ph.AddControlsReturnThis(test2(setTest2));

                addMessageIfNotNull(ph, getTest3(null));
                ph.AddControlsReturnThis(test3(setTest3));

                addMessageIfNotNull(ph, getTest4(null));
                ph.AddControlsReturnThis(test4(setTest4));

                addMessageIfNotNull(ph, getTest5(null));
                ph.AddControlsReturnThis(test5(setTest5));

                addMessageIfNotNull(ph, getTest6(null));
                ph.AddControlsReturnThis(test6(setTest6));

                var table = FormItemBlock.CreateFormItemTable();
                table.AddFormItems(
                    FormItem.Create("Textarea", new EwfTextBox("This is a paragraph.", rows: 4)),
                    FormItem.Create("Masked Input", new EwfTextBox("This should not appear in the markup!", masksCharacters: true)));
                ph.AddControlsReturnThis(table);

                EwfUiStatics.SetContentFootActions(
                    new ActionButtonSetup("OK", new PostBackButton()),
                    new ActionButtonSetup(
                        "Reset Values",
                        new PostBackButton(
                            PostBack.CreateFull(
                                id: "reset",
                                firstModificationMethod: () => {
                    setTest1(null);
                    setTest2(null);
                    setTest3(null);
                    setTest4(null);
                    setTest5(null);
                    setTest6(null);
                }))));
            });
        }
Пример #29
0
        public View Render()
        {
            StackLayout stackLayout = new StackLayout()
            {
                Margin = new Thickness(5)
            };


            if (!string.IsNullOrWhiteSpace(Label))
            {
                Label label = new Label
                {
                    Text           = Label,
                    Margin         = new Thickness(5, 0, 0, 5),
                    FontAttributes = FontAttributes.Bold
                };

                if (ElementTextColor != null)
                {
                    label.TextColor = ElementTextColor;
                }
                stackLayout.Children.Add(label);
            }

            datePicker = new DatePicker();
            stackLayout.Children.Add(datePicker);

            if (ElementBackgroundColor != null)
            {
                datePicker.BackgroundColor = ElementBackgroundColor;
            }

            if (ElementTextColor != null)
            {
                datePicker.TextColor = ElementTextColor;
            }

            datePicker.DateSelected += (s, e) =>
            {
                if (AutoPostBack)
                {
                    PostBack?.Invoke(s, Key);
                }
            };

            View = stackLayout;
            return(View);
        }
        protected override void loadData()
        {
            FormState.ExecuteWithDataModificationsAndDefaultAction(
                PostBack.CreateFull().ToCollection(),
                () => {
                ph.AddControlsReturnThis(
                    new Section("Radio Button List, Vertical", FormItemList.CreateStack(items: getRadioItems(false).Materialize()).ToCollection())
                    .ToCollection <FlowComponent>()
                    .Append(new Section("Radio Button List, Horizontal", FormItemList.CreateStack(items: getRadioItems(true).Materialize()).ToCollection()))
                    .Append(getChosenUpgradeTestingInfo())
                    .Append(new Section("Drop-Down List", FormItemList.CreateStack(items: getDropDownItems().Materialize()).ToCollection()))
                    .GetControls());

                EwfUiStatics.SetContentFootActions(new ButtonSetup("Submit").ToCollection());
            });
        }
        protected override void loadData()
        {
            var pb = PostBack.CreateFull(
                firstModificationMethod: modifyData,
                actionGetter: () => new PostBackAction(new ExternalResourceInfo(es.info.ReturnAndDestinationUrl)));

            FormState.ExecuteWithDataModificationsAndDefaultAction(
                pb.ToCollection(),
                () => {
                newPassword = new DataValue <string>();
                ph.AddControlsReturnThis(
                    FormItemBlock.CreateFormItemTable(
                        formItems: newPassword.GetPasswordModificationFormItems(firstLabel: "New password", secondLabel: "Re-type new password")));
                EwfUiStatics.SetContentFootActions(new ActionButtonSetup("Change Password", new PostBackButton()));
            });
        }
        public List <ActionButtonSetup> CreateActionButtonSetups()
        {
            var actionButtonSetups = new List <ActionButtonSetup>();

            actionButtonSetups.Add(
                new ActionButtonSetup(
                    "Delegate action",
                    new PostBackButton(
                        PostBack.CreateFull(id: "delegate", firstModificationMethod: () => EwfPage.AddStatusMessage(StatusMessageType.Info, "Did Something.")))));
            actionButtonSetups.Add(new ActionButtonSetup("Go to Google", new EwfLink(new ExternalResourceInfo("http://www.google.com"))));
            actionButtonSetups.Add(
                new ActionButtonSetup(
                    "Generate error",
                    new PostBackButton(PostBack.CreateFull(id: "error", firstModificationMethod: () => { throw new ApplicationException(); }))));
            return(actionButtonSetups);
        }
Пример #33
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 Control GetFileLinkFromFileId(int fileId, string labelOverride = null, string textIfNoFile = "")
        {
            var file = SystemProvider.GetFile(fileId);

            if (file == null)
            {
                return(new PlaceHolder().AddControlsReturnThis(textIfNoFile.ToComponents().GetControls()));
            }
            return(new PostBackButton(
                       new TextActionControlStyle(labelOverride ?? file.FileName),
                       usesSubmitBehavior: false,
                       postBack:
                       PostBack.CreateFull(
                           id: PostBack.GetCompositeId("ewfFile", file.FileId.ToString()),
                           actionGetter: () => new PostBackAction(new SecondaryResponse(new BlobFileResponse(fileId, () => true), false)))));
        }
        /// <summary>
        /// Creates a post-back button.
        /// </summary>
        /// <param name="postBack">Do not pass null.</param>
        /// <param name="actionControlStyle"></param>
        /// <param name="usesSubmitBehavior">True if this button should act like a submit button (respond to the enter key). Doesn't work with the text or custom
        /// action control styles.</param>
        public PostBackButton( PostBack postBack, ActionControlStyle actionControlStyle, bool usesSubmitBehavior = true )
        {
            this.postBack = postBack;
            ActionControlStyle = actionControlStyle;
            this.usesSubmitBehavior = usesSubmitBehavior;

            EwfPage.Instance.AddControlTreeValidation(
                () => {
                    if( !this.IsOnPage() || !this.usesSubmitBehavior )
                        return;
                    var submitButtons = EwfPage.Instance.GetDescendants( EwfPage.Instance ).OfType<PostBackButton>().Where( i => i.usesSubmitBehavior ).ToArray();
                    if( submitButtons.Count() > 1 ) {
                        throw new ApplicationException(
                            "Multiple buttons with submit behavior were detected. There may only be one per page. The button IDs are " +
                            StringTools.ConcatenateWithDelimiter( ", ", submitButtons.Select( control => control.UniqueID ).ToArray() ) + "." );
                    }
                    EwfPage.Instance.SubmitButtonPostBack = this.postBack;
                } );
        }
        /// <summary>
        /// Creates a text box.
        /// </summary>
        /// <param name="value">Do not pass null.</param>
        /// <param name="rows">The number of rows in the text box.</param>
        /// <param name="masksCharacters">Pass true to mask characters entered in the text box. Has no effect when there is more than one row in the text box.
        /// </param>
        /// <param name="maxLength">The maximum number of characters that can be entered in this text box.</param>
        /// <param name="readOnly">Pass true to prevent the contents of the text box from being changed.</param>
        /// <param name="disableBrowserAutoComplete">If true, prevents the browser from displaying values the user previously entered. Keep in mind that there is
        /// currently an "arms race" taking place over forms auto-complete. Banks and other "high-security" organizations keep looking for ways to disable
        /// auto-complete on their login forms while browsers and password managers are always trying to preserve this functionality for their users. Because of
        /// this war, it's possible that your request to disable auto-complete will be ignored. See http://stackoverflow.com/a/23234498/35349 for more information.
        /// </param>
        /// <param name="suggestSpellCheck">By default, Firefox does not spell check single-line text boxes. By default, Firefox does spell check multi-line text
        /// boxes. Setting this parameter to a value will set the spellcheck attribute on the text box to enable/disable spell checking, if the user agent supports
        /// it.</param>
        /// <param name="postBack">The post-back that will be performed when the user hits Enter on the text box or selects an auto-complete item.</param>
        /// <param name="autoPostBack">Pass true to cause an automatic post-back when the text box loses focus.</param>
        public EwfTextBox(
            string value, int rows = 1, bool masksCharacters = false, int? maxLength = null, bool readOnly = false, bool disableBrowserAutoComplete = false,
            bool? suggestSpellCheck = null, PostBack postBack = null, bool autoPostBack = false)
        {
            this.rows = rows;
            this.masksCharacters = masksCharacters;
            this.maxLength = maxLength;
            this.readOnly = readOnly;
            this.disableBrowserAutoComplete = disableBrowserAutoComplete;
            this.suggestSpellCheck = suggestSpellCheck;

            if( value == null )
                throw new ApplicationException( "You cannot create a text box with a null value. Please use the empty string instead." );
            formValue = new FormValue<string>(
                () => value,
                () => this.IsOnPage() ? UniqueID : "",
                v => v,
                rawValue =>
                rawValue != null ? PostBackValueValidationResult<string>.CreateValidWithValue( rawValue ) : PostBackValueValidationResult<string>.CreateInvalid() );

            this.postBack = postBack;
            this.autoPostBack = autoPostBack;
        }
        void ControlTreeDataLoader.LoadData()
        {
            var isTextarea = rows > 1;
            textBox = new WebControl( isTextarea ? HtmlTextWriterTag.Textarea : HtmlTextWriterTag.Input );
            PreRender += delegate {
                if( !isTextarea )
                    textBox.Attributes.Add( "type", masksCharacters ? "password" : "text" );
                textBox.Attributes.Add( "name", UniqueID );
                if( isTextarea )
                    textBox.Attributes.Add( "rows", rows.ToString() );
                if( maxLength.HasValue )
                    textBox.Attributes.Add( "maxlength", maxLength.Value.ToString() );
                if( readOnly )
                    textBox.Attributes.Add( "readonly", "readonly" );
                if( disableBrowserAutoComplete || autoCompleteService != null )
                    textBox.Attributes.Add( "autocomplete", "off" );
                if( suggestSpellCheck.HasValue )
                    textBox.Attributes.Add( "spellcheck", suggestSpellCheck.Value.ToString().ToLower() );

                var value = formValue.GetValue( AppRequestState.Instance.EwfPageRequestState.PostBackValues );
                var valueOrWatermark = watermarkText.Any() && !value.Any() ? watermarkText : value;
                if( isTextarea )
                    AddTextareaValue( textBox, valueOrWatermark );
                else if( !masksCharacters )
                    textBox.Attributes.Add( "value", valueOrWatermark );
            };
            Controls.Add( textBox );

            if( watermarkText.Any() ) {
                textBox.AddJavaScriptEventScript( JsWritingMethods.onfocus, "if( value == '" + watermarkText + "' ) value = ''" );
                textBox.AddJavaScriptEventScript( JsWritingMethods.onblur, "if( value == '' ) value = '" + watermarkText + "'" );
                EwfPage.Instance.ClientScript.RegisterOnSubmitStatement(
                    GetType(),
                    UniqueID + "watermark",
                    "$( '#" + textBox.ClientID + "' ).filter( function() { return this.value == '" + watermarkText + "'; } ).val( '' )" );
            }

            var jsNeededForImplicitSubmission = postBack != null || autoPostBack ||
                                                ( autoCompleteService != null && autoCompleteOption == AutoCompleteOption.PostBackOnTextChangeAndItemSelect );
            if( postBack == null && ( autoPostBack || ( autoCompleteService != null && autoCompleteOption != AutoCompleteOption.NoPostBack ) ) )
                postBack = EwfPage.Instance.DataUpdatePostBack;

            if( postBack != null )
                EwfPage.Instance.AddPostBack( postBack );
            PreRender += delegate { PostBackButton.EnsureImplicitSubmission( this, jsNeededForImplicitSubmission ? postBack : null ); };

            if( autoPostBack || ( autoCompleteService != null && autoCompleteOption == AutoCompleteOption.PostBackOnTextChangeAndItemSelect ) ) {
                PreRender += delegate {
                    // Use setTimeout to prevent keypress and change from *both* triggering post-backs at the same time when Enter is pressed after a text change.
                    textBox.AddJavaScriptEventScript(
                        JsWritingMethods.onchange,
                        "setTimeout( function() { " + PostBackButton.GetPostBackScript( postBack, includeReturnFalse: false ) + "; }, 0 )" );
                };
            }

            if( ToolTip != null || ToolTipControl != null )
                new ToolTip( ToolTipControl ?? EnterpriseWebFramework.Controls.ToolTip.GetToolTipTextControl( ToolTip ), textBox );
        }
 /// <summary>
 /// Creates a script that performs a post-back.
 /// </summary>
 /// <param name="postBack">Do not pass null.</param>
 public static ClickScript CreatePostBackScript( PostBack postBack )
 {
     return new ClickScript { postBack = postBack };
 }
        /// <summary>
        /// Ensures that the specified control will submit the form when the enter key is pressed while the control has focus. Specify null for the post-back to
        /// rely on HTML's built-in implicit submission behavior, which will simulate a click on the submit button.
        /// </summary>
        internal static void EnsureImplicitSubmission( WebControl control, PostBack postBack, string predicate = "" )
        {
            if( postBack != null ) {
                control.AddJavaScriptEventScript(
                    JsWritingMethods.onkeypress,
                    "if( event.which == 13 " + predicate.PrependDelimiter( " && " ) + " ) { " + GetPostBackScript( postBack ) + "; }" );
                return;
            }
            if( EwfPage.Instance.SubmitButtonPostBack != null )
                return;

            var sentences = new[]
                {
                    "EWF does not allow form controls to use HTML's built-in implicit submission on a page with no submit button.", "There are two reasons for this.",
                    "First, the behavior of HTML's implicit submission appears to be somewhat arbitrary when there is no submit button; see http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#implicit-submission.",
                    "Second, we don't want the implicit submission behavior of form controls to unpredictably change if a submit button is added or removed."
                };
            throw new ApplicationException( StringTools.ConcatenateWithDelimiter( " ", sentences ) );
        }
 internal static string GetPostBackScript( PostBack postBack, bool includeReturnFalse = true )
 {
     if( EwfPage.Instance.GetPostBack( postBack.Id ) != postBack )
         throw new ApplicationException( "The post-back must have been added to the page." );
     var validationPostBack = postBack is ActionPostBack ? ( (ActionPostBack)postBack ).ValidationDm as PostBack : null;
     if( validationPostBack != null && EwfPage.Instance.GetPostBack( validationPostBack.Id ) != validationPostBack )
         throw new ApplicationException( "The post-back's validation data-modification, if it is a post-back, must have been added to the page." );
     return "postBack( '{0}' )".FormatWith( postBack.Id ) + ( includeReturnFalse ? "; return false" : "" );
 }
 /// <summary>
 /// Creates a post-back button.
 /// </summary>
 /// <param name="postBack">Do not pass null.</param>
 // This constructor is needed because of ActionButtonSetups, which take the text in the ActionButtonSetup instead of here and the submit behavior will be overridden.
 public PostBackButton( PostBack postBack )
     : this(postBack, new ButtonActionControlStyle( "" ))
 {
 }
 /// <summary>
 /// Creates a time picker. The minute interval allows the user to select values only in the given increments. 
 /// Be aware that other values can still be sent from the browser via a crafted request.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="minuteInterval"></param>
 /// <param name="postBack">The post-back that will be performed when the user hits Enter on the time picker.</param>
 public TimePicker( TimeSpan? value, int minuteInterval = 15, PostBack postBack = null )
 {
     this.value = value;
     this.minuteInterval = minuteInterval;
     this.postBack = postBack;
 }
 /// <summary>
 /// Creates a date picker.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="postBack">The post-back that will be performed when the user hits Enter on the date picker.</param>
 public DatePicker( DateTime? value, PostBack postBack = null )
 {
     this.value = value.HasValue ? value.Value.Date as DateTime? : null;
     this.postBack = postBack;
 }