Ewl » Canonical The canonical version of EWL Read More
Clone URL:  
Pushed to 2 repositories · View In Graph Contained in tip and canonical

Merge

Changeset 47b04885683c

Parents 735ad84717da

Parents f2a10e3c3401

by Profile picture of William GrossWilliam Gross

Changes to 37 files · Browse files at 47b04885683c Showing diff from parent 735ad84717da f2a10e3c3401 Diff from another changeset...

Change 1 of 4 Show Entire File Core/​Core.csproj Stacked
 
377
378
379
380
381
382
 
 
 
 
 
 
383
384
385
 
400
401
402
 
 
403
404
405
 
593
594
595
 
 
 
596
597
598
599
600
 
738
739
740
741
742
743
744
 
377
378
379
 
380
381
382
383
384
385
386
387
388
389
390
 
405
406
407
408
409
410
411
412
 
600
601
602
603
604
605
606
 
607
608
609
 
747
748
749
 
750
751
752
@@ -377,9 +377,14 @@
  <Compile Include="EnterpriseWebFramework\Error Display\Styles\ListErrorDisplayStyle.cs" />   <Compile Include="EnterpriseWebFramework\Error Display\Styles\SectionErrorDisplayStyle.cs" />   <Compile Include="EnterpriseWebFramework\EwfInitializationOps.cs" /> - <Compile Include="EnterpriseWebFramework\EwfSafeResponseWriter.cs" />   <Compile Include="EnterpriseWebFramework\FontAwesomeIcon.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Check Boxes\BlockCheckBoxSetup.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Checkboxes\Checkbox.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Checkboxes\CheckboxSetup.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Checkboxes\FlowCheckbox.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Checkboxes\FlowCheckboxSetup.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Checkboxes\FlowRadioButtonSetup.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Checkboxes\RadioButtonSetup.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Date and Time\DateAndTimeControl.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Date and Time\DateAndTimeControlSetup.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Date and Time\DateControl.cs" /> @@ -400,6 +405,8 @@
  <Compile Include="EnterpriseWebFramework\Form Controls\Imprecise Number Control\ImpreciseNumberControl.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Imprecise Number Control\ImpreciseNumberControlSetup.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Lists\ChangeBasedCheckBoxList.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Lists\Free-Form Radio List\FreeFormRadioList.cs" /> + <Compile Include="EnterpriseWebFramework\Form Controls\Lists\Free-Form Radio List\FreeFormRadioListSetup.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Lists\List Items\ChangeBasedListItem.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Lists\List Items\ChangeBasedListItemWithSelectionState.cs" />   <Compile Include="EnterpriseWebFramework\Form Controls\Lists\EwfCheckBoxList.cs" /> @@ -593,8 +600,10 @@
  <Compile Include="EnterpriseWebFramework\Page Infrastructure\SecondaryPostBackOperation.cs" />   <Compile Include="EnterpriseWebFramework\PaymentProcessing\PaymentProcessingStatics.cs" />   <Compile Include="EnterpriseWebFramework\PaymentProcessing\StatusMessageAndDestination.cs" /> + <Compile Include="EnterpriseWebFramework\Request Handling\EwfSafeRequestHandler.cs" /> + <Compile Include="EnterpriseWebFramework\Request Handling\EwfSafeResponseWriter.cs" /> + <Compile Include="EnterpriseWebFramework\Request Handling\StaticFileHandler.cs" />   <Compile Include="EnterpriseWebFramework\RevisionDisplayStatics.cs" /> - <Compile Include="EnterpriseWebFramework\StaticFileHandler.cs" />   <Compile Include="EnterpriseWebFramework\Text\EmphasizedContent.cs" />   <Compile Include="EnterpriseWebFramework\Text\ImportantContent.cs" />   <Compile Include="EnterpriseWebFramework\Text\LineBreak.cs" /> @@ -738,7 +747,6 @@
  <Compile Include="EnterpriseWebFramework\UserManagement\FormsAuthCapableUserManagementProvider.cs" />   <Compile Include="EnterpriseWebFramework\UserManagement\User.cs" />   <Compile Include="EnterpriseWebFramework\UserManagement\SystemUserManagementProvider.cs" /> - <Compile Include="EnterpriseWebFramework\Form Controls\Lists\FreeFormRadioList.cs" />   <Compile Include="Tools\CollectionTools.cs" />   <Compile Include="Collections\ListSet.cs" />   <Compile Include="FormattingMethods.cs" />
 
26
27
28
 
29
30
31
32
33
34
 
35
36
37
 
74
75
76
 
77
78
79
 
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
76
77
78
79
80
81
82
@@ -26,12 +26,14 @@
  <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cerror_0020display_0020styles/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cerror_0020display_005Cstyles/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CForm_0020Controls/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cform_0020controls_005Ccheckboxes/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CForm_0020Controls_005CCheck_0020Boxes/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cform_0020controls_005Cdate_0020and_0020time/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cform_0020controls_005Cemail_0020address_0020control/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cform_0020controls_005Chtml_0020editor/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cform_0020controls_005Cimprecise_0020number_0020control/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CForm_0020Controls_005CLists/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cform_0020controls_005Clists_005Cfree_002Dform_0020radio_0020list/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CForm_0020Controls_005CLists_005CList_0020Items/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CForm_0020Controls_005CLists_005CSelect_0020List/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cform_0020controls_005Cnavigational_0020form_0020control/@EntryIndexedValue">True</s:Boolean> @@ -74,6 +76,7 @@
  <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cpage_0020infrastructure_005Cpage_0020structure_005Cnodes/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Cpage_0020infrastructure_005Cpartial_0020updating/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CPaymentProcessing/@EntryIndexedValue">True</s:Boolean> + <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Crequest_0020handling/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CResource_0020Meta_0020Logic/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=EnterpriseWebFramework_005CResource_0020Meta_0020Logic_005CAlternative_0020Resource_0020Modes/@EntryIndexedValue">True</s:Boolean>   <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=enterprisewebframework_005Ctext/@EntryIndexedValue">True</s:Boolean>
 
57
58
59
60
 
61
62
63
 
123
124
125
126
127
 
 
128
129
130
 
57
58
59
 
60
61
62
63
 
123
124
125
 
 
126
127
128
129
130
@@ -57,7 +57,7 @@
  b.AddFormItems( Email.ToEmailAddressControl( false, value: user != null ? user.Email : "" ).ToFormItem( label: "Email address".ToComponents() ) );     if( includePasswordControls() ) { - var group = new RadioButtonGroup( false ); + var group = new LegacyRadioButtonGroup( false );     var keepPassword = FormItem.Create(   "", @@ -123,8 +123,8 @@
  FormItem.Create(   "Role",   SelectList.CreateDropDown( from i in availableRoles select SelectListItem.Create( i.RoleId as int?, i.Name ), user?.Role.RoleId ), - validationGetter: control => - new EwfValidation( ( pbv, validator ) => RoleId.Value = control.ValidateAndGetSelectedItemIdInPostBack( pbv, validator ) ?? default( int ) ) ) ); + validationGetter: control => new EwfValidation( + ( pbv, validator ) => RoleId.Value = control.ValidateAndGetSelectedItemIdInPostBack( pbv, validator ) ?? default( int ) ) ) );     Controls.Add( b );   }
 
10
11
12
13
14
15
 
16
17
18
 
10
11
12
 
 
 
13
14
15
16
@@ -10,9 +10,7 @@
 using EnterpriseWebLibrary.InputValidation;    namespace EnterpriseWebLibrary.EnterpriseWebFramework { - /// <summary> - /// A block-level check box with the label vertically centered on the box. - /// </summary> + [ Obsolete( "Guaranteed through 28 Feb 2019. Use Checkbox instead." ) ]   [ ParseChildren( ChildrenAsProperties = true, DefaultProperty = "NestedControls" ) ]   public class BlockCheckBox: WebControl, CommonCheckBox, ControlTreeDataLoader, FormValueControl, ControlWithJsInitLogic, FormControl<FlowComponent> {   private readonly FormValue<bool> checkBoxFormValue;
 
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
23
24
25
 
38
39
40
41
42
43
44
45
 
 
46
47
48
 
6
7
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
10
11
12
 
25
26
27
 
 
 
 
 
28
29
30
31
32
@@ -6,20 +6,7 @@
 using EnterpriseWebLibrary.JavaScriptWriting;    namespace EnterpriseWebLibrary.EnterpriseWebFramework { - /* NOTE: This should be named InlineCheckBox. When we do this, rename CommonCheckBox to EwfCheckBox. - * - * InlineCheckBox is a check box that can be centered with text-align or used within a paragraph of text. This cannot be done with BlockCheckBox for two reasons: - * - * 1. BlockCheckBox needs to have 100% width in order for nested controls to work properly in Chrome and Safari. Specifically, a two-row shrink wrap table with wide content - * in the second column of the second row did not work properly in these browsers under certain circumstances (Sam may have details). Inline elements cannot specify width, - * so the BlockCheckBox must be non-inline, and non-inline elements cannot be centered with text-align or used within a paragraph of text. - * - * 2. We could not find a way to get Chrome and Safari to center a table-based check box control using text-align regardless of what CSS display value we used on the element. - * */ - - /// <summary> - /// An in-line check box with the label vertically centered on the box. - /// </summary> + [ Obsolete( "Guaranteed through 28 Feb 2019. Use Checkbox instead." ) ]   public class EwfCheckBox: WebControl, CommonCheckBox, ControlTreeDataLoader, FormValueControl {   private static readonly ElementClass elementClass = new ElementClass( "ewfCheckBox" );   @@ -38,11 +25,8 @@
  () => isChecked,   () => checkBox.IsOnPage() ? checkBox.UniqueID : "",   v => v.ToString(), - rawValue => rawValue == null - ? PostBackValueValidationResult<bool>.CreateValid( false ) - : rawValue == "on" - ? PostBackValueValidationResult<bool>.CreateValid( true ) - : PostBackValueValidationResult<bool>.CreateInvalid() ); + rawValue => rawValue == null ? PostBackValueValidationResult<bool>.CreateValid( false ) : + rawValue == "on" ? PostBackValueValidationResult<bool>.CreateValid( true ) : PostBackValueValidationResult<bool>.CreateInvalid() );   }     internal static void AddCheckBoxAttributes(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
 
@@ -0,0 +1,154 @@
+using System; +using System.Collections.Generic; +using System.Linq; +using EnterpriseWebLibrary.InputValidation; +using Humanizer; +using JetBrains.Annotations; + +namespace EnterpriseWebLibrary.EnterpriseWebFramework { + /// <summary> + /// A two-state control (i.e. checkbox). + /// </summary> + public class Checkbox: FormControl<PhrasingComponent> { + private static readonly ElementClass elementClass = new ElementClass( "ewfCb" ); + + [ UsedImplicitly ] + private class CssElementCreator: ControlCssElementCreator { + IReadOnlyCollection<CssElement> ControlCssElementCreator.CreateCssElements() => + new CssElement( "Checkbox", "label.{0}".FormatWith( elementClass.ClassName ) ).ToCollection() + .Append( new CssElement( "CheckboxControl", "input.{0}".FormatWith( elementClass.ClassName ) ) ) + .Append( new CssElement( "CheckboxLabel", "span.{0}".FormatWith( elementClass.ClassName ) ) ) + .Materialize(); + } + + public PhrasingComponent PageComponent { get; } + public EwfValidation Validation { get; } + + /// <summary> + /// Creates a checkbox. + /// </summary> + /// <param name="value"></param> + /// <param name="label">The checkbox label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the checkbox.</param> + /// <param name="validationMethod">The validation method. Pass null if you’re only using this control for page modification.</param> + public Checkbox( + bool value, IReadOnlyCollection<PhrasingComponent> label, CheckboxSetup setup = null, Action<PostBackValue<bool>, Validator> validationMethod = null ) { + setup = setup ?? CheckboxSetup.Create(); + + var id = new ElementId(); + var formValue = new FormValue<bool>( + () => value, + () => setup.IsReadOnly ? "" : id.Id, + v => v.ToString(), + rawValue => rawValue == null ? PostBackValueValidationResult<bool>.CreateValid( false ) : + rawValue == "on" ? PostBackValueValidationResult<bool>.CreateValid( true ) : PostBackValueValidationResult<bool>.CreateInvalid() ); + + PageComponent = getComponent( + formValue, + id, + null, + setup.DisplaySetup, + setup.IsReadOnly, + setup.Classes, + setup.PageModificationValue, + label, + setup.Action, + setup.ValueChangedAction, + () => ( setup.ValueChangedAction?.GetJsStatements() ?? "" ).ConcatenateWithSpace( + setup.PageModificationValue.GetJsModificationStatements( "this.checked" ) ) ); + + formValue.AddPageModificationValue( setup.PageModificationValue, v => v ); + + if( validationMethod != null ) + Validation = formValue.CreateValidation( validationMethod ); + } + + /// <summary> + /// Creates a radio button. + /// </summary> + internal Checkbox( + FormValue<ElementId> formValue, ElementId id, RadioButtonSetup setup, IReadOnlyCollection<PhrasingComponent> label, FormAction selectionChangedAction, + Func<string> jsClickStatementGetter, EwfValidation validation, string listItemId = null ) { + PageComponent = getComponent( + formValue, + id, + listItemId, + setup.DisplaySetup, + setup.IsReadOnly, + setup.Classes, + setup.PageModificationValue, + label, + setup.Action, + selectionChangedAction, + () => setup.IsReadOnly + ? "" + : ( setup.PageModificationValue.Value ? "" : selectionChangedAction?.GetJsStatements() ?? "" ) + .ConcatenateWithSpace( jsClickStatementGetter() ) ); + Validation = validation; + } + + private PhrasingComponent getComponent( + FormValue formValue, ElementId id, string radioButtonListItemId, DisplaySetup displaySetup, bool isReadOnly, ElementClassSet classes, + PageModificationValue<bool> pageModificationValue, IReadOnlyCollection<PhrasingComponent> label, FormAction action, FormAction valueChangedAction, + Func<string> jsClickStatementGetter ) { + return new CustomPhrasingComponent( + new DisplayableElement( + labelContext => new DisplayableElementData( + displaySetup, + () => new DisplayableElementLocalData( "label" ), + classes: elementClass.Add( classes ?? ElementClassSet.Empty ), + children: new DisplayableElement( + context => { + id.AddId( context.Id ); + + if( !isReadOnly ) { + action.AddToPageIfNecessary(); + valueChangedAction?.AddToPageIfNecessary(); + } + + return new DisplayableElementData( + null, + () => { + var attributes = new List<Tuple<string, string>>(); + var radioButtonFormValue = formValue as FormValue<ElementId>; + attributes.Add( Tuple.Create( "type", radioButtonFormValue != null ? "radio" : "checkbox" ) ); + if( radioButtonFormValue != null || !isReadOnly ) + attributes.Add( + Tuple.Create( "name", radioButtonFormValue != null ? ( (FormValue)radioButtonFormValue ).GetPostBackValueKey() : context.Id ) ); + if( radioButtonFormValue != null ) + attributes.Add( Tuple.Create( "value", radioButtonListItemId ?? context.Id ) ); + if( pageModificationValue.Value ) + attributes.Add( Tuple.Create( "checked", "checked" ) ); + if( isReadOnly ) + attributes.Add( Tuple.Create( "disabled", "disabled" ) ); + + var jsInitStatements = StringTools.ConcatenateWithDelimiter( + " ", + !isReadOnly + ? SubmitButton.GetImplicitSubmissionKeyPressStatements( action, false ) + .Surround( "$( '#{0}' ).keypress( function( e ) {{ ".FormatWith( context.Id ), " } );" ) + : "", + jsClickStatementGetter().Surround( "$( '#{0}' ).click( function() {{ ".FormatWith( context.Id ), " } );" ) ); + + return new DisplayableElementLocalData( + "input", + new FocusabilityCondition( true ), + isFocused => { + if( isFocused ) + attributes.Add( Tuple.Create( "autofocus", "autofocus" ) ); + return new DisplayableElementFocusDependentData( + attributes: attributes, + includeIdAttribute: true, + jsInitStatements: jsInitStatements ); + } ); + }, + classes: elementClass ); + }, + formValue: formValue ).ToCollection() + .Concat( label.Any() ? new GenericPhrasingContainer( label, classes: elementClass ).ToCollection() : Enumerable.Empty<FlowComponent>() ) + .Materialize() ) ).ToCollection() ); + } + + FormControlLabeler FormControl<PhrasingComponent>.Labeler => null; + } +} \ No newline at end of file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
@@ -0,0 +1,47 @@
+namespace EnterpriseWebLibrary.EnterpriseWebFramework { + /// <summary> + /// The configuration for a checkbox. + /// </summary> + public class CheckboxSetup { + /// <summary> + /// Creates a setup object for a standard checkbox. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the control.</param> + /// <param name="action">The action that will occur when the user hits Enter on the control. Pass null to use the current default action.</param> + /// <param name="valueChangedAction">The action that will occur when the value is changed. Pass null for no action.</param> + /// <param name="pageModificationValue"></param> + public static CheckboxSetup Create( + DisplaySetup displaySetup = null, ElementClassSet classes = null, FormAction action = null, FormAction valueChangedAction = null, + PageModificationValue<bool> pageModificationValue = null ) { + return new CheckboxSetup( displaySetup, false, classes, action, valueChangedAction, pageModificationValue ); + } + + /// <summary> + /// Creates a setup object for a read-only checkbox. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the control.</param> + public static CheckboxSetup CreateReadOnly( DisplaySetup displaySetup = null, ElementClassSet classes = null ) { + return new CheckboxSetup( displaySetup, true, classes, null, null, null ); + } + + internal readonly DisplaySetup DisplaySetup; + internal readonly bool IsReadOnly; + internal readonly ElementClassSet Classes; + internal readonly FormAction Action; + internal readonly FormAction ValueChangedAction; + internal readonly PageModificationValue<bool> PageModificationValue; + + private CheckboxSetup( + DisplaySetup displaySetup, bool isReadOnly, ElementClassSet classes, FormAction action, FormAction valueChangedAction, + PageModificationValue<bool> pageModificationValue ) { + DisplaySetup = displaySetup; + IsReadOnly = isReadOnly; + Classes = classes; + Action = action ?? FormState.Current.DefaultAction; + ValueChangedAction = valueChangedAction; + PageModificationValue = pageModificationValue ?? new PageModificationValue<bool>(); + } + } +} \ No newline at end of file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
 
@@ -0,0 +1,100 @@
+using System; +using System.Collections.Generic; +using System.Linq; +using EnterpriseWebLibrary.InputValidation; +using Humanizer; +using JetBrains.Annotations; + +namespace EnterpriseWebLibrary.EnterpriseWebFramework { + /// <summary> + /// A checkbox that supports nested components. + /// </summary> + public class FlowCheckbox: FormControl<FlowComponent> { + private static readonly ElementClass unhighlightedClass = new ElementClass( "ewfFcu" ); + private static readonly ElementClass highlightedClass = new ElementClass( "ewfFch" ); + private static readonly ElementClass nestedContentClass = new ElementClass( "ewfFcc" ); + + [ UsedImplicitly ] + private class CssElementCreator: ControlCssElementCreator { + IReadOnlyCollection<CssElement> ControlCssElementCreator.CreateCssElements() => + new[] + { + new CssElement( "FlowCheckboxAllStates", new[] { unhighlightedClass, highlightedClass }.Select( getSelector ).ToArray() ), + new CssElement( "FlowCheckboxUnhighlightedState", getSelector( unhighlightedClass ) ), + new CssElement( "FlowCheckboxHighlightedState", getSelector( highlightedClass ) ), + new CssElement( "FlowCheckboxNestedContentContainer", "div.{0}".FormatWith( nestedContentClass.ClassName ) ) + }; + + private string getSelector( ElementClass elementClass ) => "div.{0}".FormatWith( elementClass.ClassName ); + } + + public FlowComponent PageComponent { get; } + public EwfValidation Validation { get; } + + /// <summary> + /// Creates a checkbox. + /// </summary> + /// <param name="value"></param> + /// <param name="label">The checkbox label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the flow checkbox.</param> + /// <param name="validationMethod">The validation method. Pass null if you’re only using the checkbox for page modification.</param> + public FlowCheckbox( + bool value, IReadOnlyCollection<PhrasingComponent> label, FlowCheckboxSetup setup = null, + Action<PostBackValue<bool>, Validator> validationMethod = null ) { + setup = setup ?? FlowCheckboxSetup.Create(); + + var checkbox = new Checkbox( value, label, setup: setup.CheckboxSetup, validationMethod: validationMethod ); + + PageComponent = getComponent( + setup.DisplaySetup, + setup.Classes, + setup.CheckboxSetup.PageModificationValue, + checkbox, + setup.HighlightedWhenChecked, + setup.NestedContentGetter, + setup.NestedContentAlwaysDisplayed ); + + Validation = checkbox.Validation; + } + + /// <summary> + /// Creates a radio button. + /// </summary> + internal FlowCheckbox( FlowRadioButtonSetup setup, Checkbox checkbox ) { + PageComponent = getComponent( + setup.DisplaySetup, + setup.Classes, + setup.RadioButtonSetup.PageModificationValue, + checkbox, + setup.HighlightedWhenSelected, + setup.NestedContentGetter, + setup.NestedContentAlwaysDisplayed ); + + Validation = checkbox.Validation; + } + + private FlowComponent getComponent( + DisplaySetup displaySetup, ElementClassSet classes, PageModificationValue<bool> pageModificationValue, Checkbox checkbox, bool highlightedWhenChecked, + Func<IReadOnlyCollection<FlowComponent>> nestedContentGetter, bool nestedContentAlwaysDisplayed ) { + var nestedContent = nestedContentGetter?.Invoke() ?? Enumerable.Empty<FlowComponent>().Materialize(); + return new GenericFlowContainer( + checkbox.PageComponent.ToCollection() + .Concat( + nestedContent.Any() + ? new GenericFlowContainer( + nestedContent, + displaySetup: nestedContentAlwaysDisplayed ? null : pageModificationValue.ToCondition().ToDisplaySetup(), + classes: nestedContentClass ).ToCollection() + : Enumerable.Empty<FlowComponent>() ) + .Materialize(), + displaySetup: displaySetup, + classes: ( highlightedWhenChecked + ? pageModificationValue.ToCondition( isTrueWhenValueSet: false ) + .ToElementClassSet( unhighlightedClass ) + .Add( pageModificationValue.ToCondition().ToElementClassSet( highlightedClass ) ) + : unhighlightedClass ).Add( classes ?? ElementClassSet.Empty ) ); + } + + FormControlLabeler FormControl<FlowComponent>.Labeler => null; + } +} \ No newline at end of file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 
@@ -0,0 +1,71 @@
+using System; +using System.Collections.Generic; + +namespace EnterpriseWebLibrary.EnterpriseWebFramework { + /// <summary> + /// The configuration for a flow checkbox. + /// </summary> + public class FlowCheckboxSetup { + /// <summary> + /// Creates a setup object for a standard checkbox. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the container.</param> + /// <param name="highlightedWhenChecked"></param> + /// <param name="action">The action that will occur when the user hits Enter on the checkbox. Pass null to use the current default action.</param> + /// <param name="valueChangedAction">The action that will occur when the checkbox value is changed. Pass null for no action.</param> + /// <param name="pageModificationValue"></param> + /// <param name="nestedContentGetter">A function that gets the content that will appear beneath the checkbox.</param> + /// <param name="nestedContentAlwaysDisplayed">Pass true to force the nested content to always be displayed instead of only when the box is checked.</param> + public static FlowCheckboxSetup Create( + DisplaySetup displaySetup = null, ElementClassSet classes = null, bool highlightedWhenChecked = false, FormAction action = null, + FormAction valueChangedAction = null, PageModificationValue<bool> pageModificationValue = null, + Func<IReadOnlyCollection<FlowComponent>> nestedContentGetter = null, bool nestedContentAlwaysDisplayed = false ) { + return new FlowCheckboxSetup( + displaySetup, + classes, + CheckboxSetup.Create( action: action, valueChangedAction: valueChangedAction, pageModificationValue: pageModificationValue ), + highlightedWhenChecked, + nestedContentGetter, + nestedContentAlwaysDisplayed ); + } + + /// <summary> + /// Creates a setup object for a read-only checkbox. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the container.</param> + /// <param name="highlightedWhenChecked"></param> + /// <param name="nestedContentGetter">A function that gets the content that will appear beneath the checkbox.</param> + /// <param name="nestedContentAlwaysDisplayed">Pass true to force the nested content to always be displayed instead of only when the box is checked.</param> + public static FlowCheckboxSetup CreateReadOnly( + DisplaySetup displaySetup = null, ElementClassSet classes = null, bool highlightedWhenChecked = false, + Func<IReadOnlyCollection<FlowComponent>> nestedContentGetter = null, bool nestedContentAlwaysDisplayed = false ) { + return new FlowCheckboxSetup( + displaySetup, + classes, + CheckboxSetup.CreateReadOnly(), + highlightedWhenChecked, + nestedContentGetter, + nestedContentAlwaysDisplayed ); + } + + internal readonly DisplaySetup DisplaySetup; + internal readonly ElementClassSet Classes; + internal readonly CheckboxSetup CheckboxSetup; + internal readonly bool HighlightedWhenChecked; + internal readonly Func<IReadOnlyCollection<FlowComponent>> NestedContentGetter; + internal readonly bool NestedContentAlwaysDisplayed; + + private FlowCheckboxSetup( + DisplaySetup displaySetup, ElementClassSet classes, CheckboxSetup checkboxSetup, bool highlightedWhenChecked, + Func<IReadOnlyCollection<FlowComponent>> nestedContentGetter, bool nestedContentAlwaysDisplayed ) { + DisplaySetup = displaySetup; + Classes = classes; + CheckboxSetup = checkboxSetup; + HighlightedWhenChecked = highlightedWhenChecked; + NestedContentGetter = nestedContentGetter; + NestedContentAlwaysDisplayed = nestedContentAlwaysDisplayed; + } + } +} \ No newline at end of file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 
@@ -0,0 +1,72 @@
+using System; +using System.Collections.Generic; + +namespace EnterpriseWebLibrary.EnterpriseWebFramework { + /// <summary> + /// The configuration for a flow radio button. + /// </summary> + public class FlowRadioButtonSetup { + /// <summary> + /// Creates a setup object for a standard radio button. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the container.</param> + /// <param name="highlightedWhenSelected"></param> + /// <param name="action">The action that will occur when the user hits Enter on the radio button. Pass null to use the current default action.</param> + /// <param name="pageModificationValue"></param> + /// <param name="nestedContentGetter">A function that gets the content that will appear beneath the radio button.</param> + /// <param name="nestedContentAlwaysDisplayed">Pass true to force the nested content to always be displayed instead of only when the button is selected. + /// </param> + public static FlowRadioButtonSetup Create( + DisplaySetup displaySetup = null, ElementClassSet classes = null, bool highlightedWhenSelected = false, FormAction action = null, + PageModificationValue<bool> pageModificationValue = null, Func<IReadOnlyCollection<FlowComponent>> nestedContentGetter = null, + bool nestedContentAlwaysDisplayed = false ) { + return new FlowRadioButtonSetup( + displaySetup, + classes, + RadioButtonSetup.Create( action: action, pageModificationValue: pageModificationValue ), + highlightedWhenSelected, + nestedContentGetter, + nestedContentAlwaysDisplayed ); + } + + /// <summary> + /// Creates a setup object for a read-only radio button. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the container.</param> + /// <param name="highlightedWhenSelected"></param> + /// <param name="nestedContentGetter">A function that gets the content that will appear beneath the radio button.</param> + /// <param name="nestedContentAlwaysDisplayed">Pass true to force the nested content to always be displayed instead of only when the button is selected. + /// </param> + public static FlowRadioButtonSetup CreateReadOnly( + DisplaySetup displaySetup = null, ElementClassSet classes = null, bool highlightedWhenSelected = false, + Func<IReadOnlyCollection<FlowComponent>> nestedContentGetter = null, bool nestedContentAlwaysDisplayed = false ) { + return new FlowRadioButtonSetup( + displaySetup, + classes, + RadioButtonSetup.CreateReadOnly(), + highlightedWhenSelected, + nestedContentGetter, + nestedContentAlwaysDisplayed ); + } + + internal readonly DisplaySetup DisplaySetup; + internal readonly ElementClassSet Classes; + internal readonly RadioButtonSetup RadioButtonSetup; + internal readonly bool HighlightedWhenSelected; + internal readonly Func<IReadOnlyCollection<FlowComponent>> NestedContentGetter; + internal readonly bool NestedContentAlwaysDisplayed; + + private FlowRadioButtonSetup( + DisplaySetup displaySetup, ElementClassSet classes, RadioButtonSetup radioButtonSetup, bool highlightedWhenSelected, + Func<IReadOnlyCollection<FlowComponent>> nestedContentGetter, bool nestedContentAlwaysDisplayed ) { + DisplaySetup = displaySetup; + Classes = classes; + RadioButtonSetup = radioButtonSetup; + HighlightedWhenSelected = highlightedWhenSelected; + NestedContentGetter = nestedContentGetter; + NestedContentAlwaysDisplayed = nestedContentAlwaysDisplayed; + } + } +} \ No newline at end of file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 
@@ -0,0 +1,42 @@
+namespace EnterpriseWebLibrary.EnterpriseWebFramework { + /// <summary> + /// The configuration for a radio button. + /// </summary> + public class RadioButtonSetup { + /// <summary> + /// Creates a setup object for a standard radio button. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the control.</param> + /// <param name="action">The action that will occur when the user hits Enter on the control. Pass null to use the current default action.</param> + /// <param name="pageModificationValue"></param> + public static RadioButtonSetup Create( + DisplaySetup displaySetup = null, ElementClassSet classes = null, FormAction action = null, PageModificationValue<bool> pageModificationValue = null ) { + return new RadioButtonSetup( displaySetup, false, classes, action, pageModificationValue ); + } + + /// <summary> + /// Creates a setup object for a read-only radio button. + /// </summary> + /// <param name="displaySetup"></param> + /// <param name="classes">The classes on the control.</param> + public static RadioButtonSetup CreateReadOnly( DisplaySetup displaySetup = null, ElementClassSet classes = null ) { + return new RadioButtonSetup( displaySetup, true, classes, null, null ); + } + + internal readonly DisplaySetup DisplaySetup; + internal readonly bool IsReadOnly; + internal readonly ElementClassSet Classes; + internal readonly FormAction Action; + internal readonly PageModificationValue<bool> PageModificationValue; + + private RadioButtonSetup( + DisplaySetup displaySetup, bool isReadOnly, ElementClassSet classes, FormAction action, PageModificationValue<bool> pageModificationValue ) { + DisplaySetup = displaySetup; + IsReadOnly = isReadOnly; + Classes = classes; + Action = action ?? FormState.Current.DefaultAction; + PageModificationValue = pageModificationValue ?? new PageModificationValue<bool>(); + } + } +} \ No newline at end of file
 
411
412
413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
415
416
 
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
@@ -411,6 +411,180 @@
  }     /// <summary> + /// Creates a checkbox for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="label">The checkbox label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the checkbox.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static Checkbox ToCheckbox( + this DataValue<bool> dataValue, IReadOnlyCollection<PhrasingComponent> label, CheckboxSetup setup = null, bool? value = null, + Action<Validator> additionalValidationMethod = null ) { + return new Checkbox( + value ?? dataValue.Value, + label, + setup: setup, + validationMethod: ( postBackValue, validator ) => { + dataValue.Value = postBackValue.Value; + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary> + /// Creates a checkbox for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="label">The checkbox label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the checkbox.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static Checkbox ToCheckbox( + this DataValue<decimal> dataValue, IReadOnlyCollection<PhrasingComponent> label, CheckboxSetup setup = null, decimal? value = null, + Action<Validator> additionalValidationMethod = null ) { + var boolValue = new DataValue<bool> { Value = ( value ?? dataValue.Value ).DecimalToBoolean() }; + return boolValue.ToCheckbox( + label, + setup: setup, + additionalValidationMethod: validator => { + dataValue.Value = boolValue.Value.BooleanToDecimal(); + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary> + /// Creates a flow checkbox for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="label">The checkbox label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the flow checkbox.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static FlowCheckbox ToFlowCheckbox( + this DataValue<bool> dataValue, IReadOnlyCollection<PhrasingComponent> label, FlowCheckboxSetup setup = null, bool? value = null, + Action<Validator> additionalValidationMethod = null ) { + return new FlowCheckbox( + value ?? dataValue.Value, + label, + setup: setup, + validationMethod: ( postBackValue, validator ) => { + dataValue.Value = postBackValue.Value; + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary> + /// Creates a flow checkbox for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="label">The checkbox label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the flow checkbox.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static FlowCheckbox ToFlowCheckbox( + this DataValue<decimal> dataValue, IReadOnlyCollection<PhrasingComponent> label, FlowCheckboxSetup setup = null, decimal? value = null, + Action<Validator> additionalValidationMethod = null ) { + var boolValue = new DataValue<bool> { Value = ( value ?? dataValue.Value ).DecimalToBoolean() }; + return boolValue.ToFlowCheckbox( + label, + setup: setup, + additionalValidationMethod: validator => { + dataValue.Value = boolValue.Value.BooleanToDecimal(); + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary> + /// Creates a radio button for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="group">The group of which this radio button will be a part. Do not pass null.</param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the radio button.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static Checkbox ToRadioButton( + this DataValue<bool> dataValue, RadioButtonGroup group, IReadOnlyCollection<PhrasingComponent> label, RadioButtonSetup setup = null, bool? value = null, + Action<Validator> additionalValidationMethod = null ) { + return group.CreateRadioButton( + value ?? dataValue.Value, + label, + setup: setup, + validationMethod: ( postBackValue, validator ) => { + dataValue.Value = postBackValue.Value; + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary> + /// Creates a radio button for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="group">The group of which this radio button will be a part. Do not pass null.</param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the radio button.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static Checkbox ToRadioButton( + this DataValue<decimal> dataValue, RadioButtonGroup group, IReadOnlyCollection<PhrasingComponent> label, RadioButtonSetup setup = null, + decimal? value = null, Action<Validator> additionalValidationMethod = null ) { + var boolValue = new DataValue<bool> { Value = ( value ?? dataValue.Value ).DecimalToBoolean() }; + return boolValue.ToRadioButton( + group, + label, + setup: setup, + additionalValidationMethod: validator => { + dataValue.Value = boolValue.Value.BooleanToDecimal(); + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary> + /// Creates a flow radio button for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="group">The group of which this radio button will be a part. Do not pass null.</param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the flow radio button.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static FlowCheckbox ToFlowRadioButton( + this DataValue<bool> dataValue, RadioButtonGroup group, IReadOnlyCollection<PhrasingComponent> label, FlowRadioButtonSetup setup = null, + bool? value = null, Action<Validator> additionalValidationMethod = null ) { + return group.CreateFlowRadioButton( + value ?? dataValue.Value, + label, + setup: setup, + validationMethod: ( postBackValue, validator ) => { + dataValue.Value = postBackValue.Value; + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary> + /// Creates a flow radio button for this data value. + /// </summary> + /// <param name="dataValue"></param> + /// <param name="group">The group of which this radio button will be a part. Do not pass null.</param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the flow radio button.</param> + /// <param name="value"></param> + /// <param name="additionalValidationMethod"></param> + public static FlowCheckbox ToFlowRadioButton( + this DataValue<decimal> dataValue, RadioButtonGroup group, IReadOnlyCollection<PhrasingComponent> label, FlowRadioButtonSetup setup = null, + decimal? value = null, Action<Validator> additionalValidationMethod = null ) { + var boolValue = new DataValue<bool> { Value = ( value ?? dataValue.Value ).DecimalToBoolean() }; + return boolValue.ToFlowRadioButton( + group, + label, + setup: setup, + additionalValidationMethod: validator => { + dataValue.Value = boolValue.Value.BooleanToDecimal(); + additionalValidationMethod?.Invoke( validator ); + } ); + } + + /// <summary>   /// Creates a block checkbox for this data value.   /// </summary>   /// <param name="dataValue"></param>
Change 1 of 7 Show Entire File Core/​EnterpriseWebFramework/​Form Controls/​Lists/​Free-Form Radio List/​FreeFormRadioList.cs Stacked
renamed from Core/EnterpriseWebFramework/Form Controls/Lists/FreeFormRadioList.cs
 
5
6
7
 
8
 
9
10
11
12
 
13
14
15
16
17
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
20
21
 
24
25
26
27
 
28
29
30
31
 
32
33
34
 
41
42
43
44
 
45
46
47
48
49
50
51
 
52
53
54
55
56
57
 
58
59
60
 
65
66
67
68
 
69
70
71
 
76
77
78
79
 
 
80
81
82
 
84
85
86
87
 
 
88
89
90
 
127
128
129
130
 
 
131
132
133
 
5
6
7
8
9
10
11
12
13
 
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
 
169
170
171
 
172
173
174
175
 
176
177
178
179
 
186
187
188
 
189
190
191
192
193
194
195
 
196
197
198
199
200
201
 
202
203
204
205
 
210
211
212
 
213
214
215
216
 
221
222
223
 
224
225
226
227
228
 
230
231
232
 
233
234
235
236
237
 
274
275
276
 
277
278
279
280
281
@@ -5,17 +5,162 @@
 using System.Web.UI;  using System.Web.UI.WebControls;  using EnterpriseWebLibrary.EnterpriseWebFramework.DisplayLinking; +using EnterpriseWebLibrary.InputValidation;  using Humanizer; +using MoreLinq;    namespace EnterpriseWebLibrary.EnterpriseWebFramework {   /// <summary> - /// A radio button list that allows you to arrange the buttons on the page however you wish. If you want access to the individual selection state of each + /// A radio-button list that allows you to arrange the buttons on the page however you wish. If you want access to the individual selection state of each   /// radio button and do not need the concept of a selected item ID for the group, use RadioButtonGroup instead.   /// </summary>   public static class FreeFormRadioList {   /// <summary>   /// Creates a free-form radio button list.   /// </summary> + /// <param name="noSelectionIsValid">Pass a value to cause a selected item ID with the default value (or the empty string when the item ID type is string) + /// to represent the state in which none of the radio buttons are selected. Note that this is not recommended by the Nielsen Norman Group; see + /// http://www.nngroup.com/articles/checkboxes-vs-radio-buttons/ for more information. If you do pass a value, passing true will cause this no-selection + /// state to be valid.</param> + /// <param name="selectedItemId"></param> + /// <param name="setup">The setup object for the free-form radio list.</param> + /// <param name="validationMethod">The validation method. Pass null if you�re only using this radio-button list for page modification.</param> + public static FreeFormRadioList<ItemIdType> Create<ItemIdType>( + bool? noSelectionIsValid, ItemIdType selectedItemId, FreeFormRadioListSetup<ItemIdType> setup = null, + Action<ItemIdType, Validator> validationMethod = null ) { + return new FreeFormRadioList<ItemIdType>( noSelectionIsValid, setup, selectedItemId, validationMethod ); + } + } + + /// <summary> + /// A radio-button list that allows you to arrange the buttons on the page however you wish. If you want access to the individual selection state of each + /// radio button and do not need the concept of a selected item ID for the group, use RadioButtonGroup instead. + /// </summary> + public class FreeFormRadioList<ItemIdType> { + private readonly FormValue<ElementId> formValue; + private readonly bool? noSelectionIsValid; + + private readonly List<( ItemIdType itemId, ElementId buttonId, bool isReadOnly, PageModificationValue<bool> pmv )> + itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples = new List<( ItemIdType, ElementId, bool, PageModificationValue<bool> )>(); + + private readonly FreeFormRadioListSetup<ItemIdType> listSetup; + private readonly EwfValidation validation; + + internal FreeFormRadioList( + bool? noSelectionIsValid, FreeFormRadioListSetup<ItemIdType> setup, ItemIdType selectedItemId, Action<ItemIdType, Validator> validationMethod ) { + setup = setup ?? FreeFormRadioListSetup.Create<ItemIdType>(); + + formValue = RadioButtonGroup.GetFormValue( + () => from i in itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples select ( i.buttonId, i.isReadOnly, EwlStatics.AreEqual( i.itemId, selectedItemId ) ), + v => getStringId( v != null ? itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples.Single( i => i.buttonId == v ).itemId : getNoSelectionItemId() ), + rawValue => from quadruple in itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples + let buttonId = quadruple.buttonId + where buttonId.Id.Any() && !quadruple.isReadOnly && getStringId( quadruple.itemId ) == rawValue + select buttonId, + noSelectionIsValid.HasValue ); + + this.noSelectionIsValid = noSelectionIsValid; + listSetup = setup; + + if( setup.ItemIdPageModificationValue != null ) + formValue.AddPageModificationValue( setup.ItemIdPageModificationValue, getItemIdFromButtonId ); + + foreach( var i in setup.ItemMatchPageModificationSetups ) + formValue.AddPageModificationValue( i.PageModificationValue, v => i.ItemIds.Contains( getItemIdFromButtonId( v ) ) ); + + if( validationMethod != null ) + validation = formValue.CreateValidation( + ( postBackValue, validator ) => { + if( setup.ValidationPredicate != null && !setup.ValidationPredicate( postBackValue.ChangedOnPostBack ) ) + return; + + var postBackItemId = getItemIdFromButtonId( postBackValue.Value ); + if( noSelectionIsValid == false && EwlStatics.AreEqual( postBackItemId, getNoSelectionItemId() ) ) { + validator.NoteErrorAndAddMessage( "Please make a selection." ); + setup.ValidationErrorNotifier?.Invoke(); + return; + } + + validationMethod( postBackItemId, validator ); + } ); + + EwfPage.Instance.AddControlTreeValidation( + () => RadioButtonGroup.ValidateControls( + noSelectionIsValid.HasValue, + EwlStatics.AreEqual( getNoSelectionItemId(), selectedItemId ), + from i in itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples select ( i.buttonId, i.isReadOnly, EwlStatics.AreEqual( i.itemId, selectedItemId ) ), + setup.DisableSingleButtonDetection ) ); + } + + private ItemIdType getItemIdFromButtonId( ElementId buttonId ) => + itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples.Where( i => i.buttonId == buttonId ) + .Select( i => i.itemId ) + .FallbackIfEmpty( getNoSelectionItemId() ) + .Single(); + + /// <summary> + /// Creates a radio button that is part of the list. + /// </summary> + /// <param name="listItemId"></param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the radio button.</param> + public Checkbox CreateRadioButton( ItemIdType listItemId, IReadOnlyCollection<PhrasingComponent> label, RadioButtonSetup setup = null ) { + setup = setup ?? RadioButtonSetup.Create(); + + validateListItem( listItemId ); + + var id = new ElementId(); + formValue.AddPageModificationValue( setup.PageModificationValue, v => v == id ); + itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples.Add( ( listItemId, id, setup.IsReadOnly, setup.PageModificationValue ) ); + + return new Checkbox( + formValue, + id, + setup, + label, + listSetup.SelectionChangedAction, + () => StringTools.ConcatenateWithDelimiter( + " ", + ( listSetup.ItemIdPageModificationValue?.GetJsModificationStatements( "'{0}'".FormatWith( getStringId( listItemId ) ) ) ?? "" ).ToCollection() + .Concat( + listSetup.ItemMatchPageModificationSetups.Select( + i => i.PageModificationValue.GetJsModificationStatements( i.ItemIds.Contains( listItemId ) ? "true" : "false" ) ) ) + .Concat( itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples.Select( i => i.pmv.GetJsModificationStatements( i.buttonId == id ? "true" : "false" ) ) ) + .ToArray() ), + null, + listItemId: getStringId( listItemId ) ); + } + + /// <summary> + /// Creates a flow radio button that is part of the list. + /// </summary> + /// <param name="listItemId"></param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the flow radio button.</param> + public FlowCheckbox CreateBlockRadioButton( ItemIdType listItemId, IReadOnlyCollection<PhrasingComponent> label, FlowRadioButtonSetup setup = null ) { + setup = setup ?? FlowRadioButtonSetup.Create(); + return new FlowCheckbox( setup, CreateRadioButton( listItemId, label, setup: setup.RadioButtonSetup ) ); + } + + private void validateListItem( ItemIdType listItemId ) { + if( noSelectionIsValid.HasValue && EwlStatics.AreEqual( listItemId, getNoSelectionItemId() ) ) + throw new ApplicationException( "You cannot create a radio button with the ID that represents no selection." ); + if( itemIdAndButtonIdAndIsReadOnlyAndPmvQuadruples.Any( i => getStringId( i.itemId ) == getStringId( listItemId ) ) ) + throw new ApplicationException( "Item IDs, when converted to strings, must be unique." ); + } + + private ItemIdType getNoSelectionItemId() => EwlStatics.GetDefaultValue<ItemIdType>( true ); + + private string getStringId( ItemIdType id ) => id.ToString(); + + public EwfValidation Validation => validation; + } + + [ Obsolete( "Guaranteed through 28 Feb 2019. Use FreeFormRadioList instead." ) ] + public static class LegacyFreeFormRadioList { + /// <summary> + /// Creates a free-form radio button list. + /// </summary>   /// <param name="allowNoSelection">Pass true to cause a selected item ID with the default value (or the empty string when the item ID type is string) to   /// represent the state in which none of the radio buttons are selected. Note that this is not recommended by the Nielsen Norman Group; see   /// http://www.nngroup.com/articles/checkboxes-vs-radio-buttons/ for more information.</param> @@ -24,11 +169,11 @@
  /// violates the HTML specification.</param>   /// <param name="itemIdPageModificationValue"></param>   /// <param name="itemMatchPageModificationSetups"></param> - public static FreeFormRadioList<ItemIdType> Create<ItemIdType>( + public static LegacyFreeFormRadioList<ItemIdType> Create<ItemIdType>(   bool allowNoSelection, ItemIdType selectedItemId, bool disableSingleButtonDetection = false,   PageModificationValue<ItemIdType> itemIdPageModificationValue = null,   IEnumerable<ListItemMatchPageModificationSetup<ItemIdType>> itemMatchPageModificationSetups = null ) { - return new FreeFormRadioList<ItemIdType>( + return new LegacyFreeFormRadioList<ItemIdType>(   allowNoSelection,   disableSingleButtonDetection,   selectedItemId, @@ -41,20 +186,20 @@
  /// A radio button list that allows you to arrange the buttons on the page however you wish. If you want access to the individual selection state of each   /// radio button and do not need the concept of a selected item ID for the group, use RadioButtonGroup instead.   /// </summary> - public class FreeFormRadioList<ItemIdType>: DisplayLink { + public class LegacyFreeFormRadioList<ItemIdType>: DisplayLink {   private readonly bool allowNoSelection;   private readonly FormValue<CommonCheckBox> formValue;   private readonly List<Action<PostBackValueDictionary>> displayLinkingSetInitialDisplayMethods = new List<Action<PostBackValueDictionary>>();   private readonly List<Action> displayLinkingAddJavaScriptMethods = new List<Action>();   private readonly List<Tuple<ItemIdType, CommonCheckBox>> itemIdsAndCheckBoxes = new List<Tuple<ItemIdType, CommonCheckBox>>();   - internal FreeFormRadioList( + internal LegacyFreeFormRadioList(   bool allowNoSelection, bool disableSingleButtonDetection, ItemIdType selectedItemId, PageModificationValue<ItemIdType> itemIdPageModificationValue,   IEnumerable<ListItemMatchPageModificationSetup<ItemIdType>> itemMatchPageModificationSetups ) {   itemMatchPageModificationSetups = itemMatchPageModificationSetups ?? ImmutableArray<ListItemMatchPageModificationSetup<ItemIdType>>.Empty;     this.allowNoSelection = allowNoSelection; - formValue = RadioButtonGroup.GetFormValue( + formValue = LegacyRadioButtonGroup.GetFormValue(   allowNoSelection,   () => from i in itemIdsAndCheckBoxes select i.Item2,   () => from i in itemIdsAndCheckBoxes where EwlStatics.AreEqual( i.Item1, selectedItemId ) select i.Item2, @@ -65,7 +210,7 @@
  select itemIdAndCheckBox.Item2 );     EwfPage.Instance.AddControlTreeValidation( - () => RadioButtonGroup.ValidateControls( + () => LegacyRadioButtonGroup.ValidateControls(   allowNoSelection,   EwlStatics.AreEqual( getNoSelectionItemId(), selectedItemId ),   itemIdsAndCheckBoxes.Select( i => i.Item2 ), @@ -76,7 +221,8 @@
  displayLinkingAddJavaScriptMethods.Add(   () => {   foreach( var pair in itemIdsAndCheckBoxes ) - pair.Item2.AddOnClickJsMethod( itemIdPageModificationValue.GetJsModificationStatements( "'{0}'".FormatWith( pair.Item1.ObjectToString( true ) ) ) ); + pair.Item2.AddOnClickJsMethod( + itemIdPageModificationValue.GetJsModificationStatements( "'{0}'".FormatWith( pair.Item1.ObjectToString( true ) ) ) );   } );   }   foreach( var setup in itemMatchPageModificationSetups ) { @@ -84,7 +230,8 @@
  displayLinkingAddJavaScriptMethods.Add(   () => {   foreach( var pair in itemIdsAndCheckBoxes ) - pair.Item2.AddOnClickJsMethod( setup.PageModificationValue.GetJsModificationStatements( setup.ItemIds.Contains( pair.Item1 ) ? "true" : "false" ) ); + pair.Item2.AddOnClickJsMethod( + setup.PageModificationValue.GetJsModificationStatements( setup.ItemIds.Contains( pair.Item1 ) ? "true" : "false" ) );   } );   }   @@ -127,7 +274,8 @@
  /// Creates a block-level radio button that is part of the list.   /// </summary>   public BlockCheckBox CreateBlockRadioButton( - ItemIdType listItemId, string label = "", FormAction action = null, bool autoPostBack = false, Func<IEnumerable<Control>> nestedControlListGetter = null ) { + ItemIdType listItemId, string label = "", FormAction action = null, bool autoPostBack = false, + Func<IEnumerable<Control>> nestedControlListGetter = null ) {   validateListItem( listItemId );   var checkBox = new BlockCheckBox(   formValue,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
@@ -0,0 +1,60 @@
+using System; +using System.Collections.Generic; +using System.Linq; + +namespace EnterpriseWebLibrary.EnterpriseWebFramework { + /// <summary> + /// The configuration for a free-form radio list. + /// </summary> + public static class FreeFormRadioListSetup { + /// <summary> + /// Creates a setup object for a free-form radio list. + /// </summary> + /// <param name="disableSingleButtonDetection">Pass true to allow just a single radio button to be displayed for this list. Use with caution, as this + /// violates the HTML specification.</param> + /// <param name="selectionChangedAction">The action that will occur when the selection is changed. Pass null for no action.</param> + /// <param name="itemIdPageModificationValue"></param> + /// <param name="itemMatchPageModificationSetups"></param> + /// <param name="validationPredicate"></param> + /// <param name="validationErrorNotifier"></param> + public static FreeFormRadioListSetup<ItemIdType> Create<ItemIdType>( + bool disableSingleButtonDetection = false, FormAction selectionChangedAction = null, PageModificationValue<ItemIdType> itemIdPageModificationValue = null, + IReadOnlyCollection<ListItemMatchPageModificationSetup<ItemIdType>> itemMatchPageModificationSetups = null, Func<bool, bool> validationPredicate = null, + Action validationErrorNotifier = null ) { + return new FreeFormRadioListSetup<ItemIdType>( + disableSingleButtonDetection, + selectionChangedAction, + itemIdPageModificationValue, + itemMatchPageModificationSetups, + validationPredicate, + validationErrorNotifier ); + } + } + + /// <summary> + /// The configuration for a free-form radio list. + /// </summary> + public class FreeFormRadioListSetup<ItemIdType> { + internal readonly bool DisableSingleButtonDetection; + internal readonly FormAction SelectionChangedAction; + internal readonly PageModificationValue<ItemIdType> ItemIdPageModificationValue; + internal readonly IReadOnlyCollection<ListItemMatchPageModificationSetup<ItemIdType>> ItemMatchPageModificationSetups; + internal readonly Func<bool, bool> ValidationPredicate; + internal readonly Action ValidationErrorNotifier; + + /// <summary> + /// Creates a setup object for a free-form radio list. + /// </summary> + internal FreeFormRadioListSetup( + bool disableSingleButtonDetection, FormAction selectionChangedAction, PageModificationValue<ItemIdType> itemIdPageModificationValue, + IReadOnlyCollection<ListItemMatchPageModificationSetup<ItemIdType>> itemMatchPageModificationSetups, Func<bool, bool> validationPredicate, + Action validationErrorNotifier ) { + DisableSingleButtonDetection = disableSingleButtonDetection; + SelectionChangedAction = selectionChangedAction; + ItemIdPageModificationValue = itemIdPageModificationValue; + ItemMatchPageModificationSetups = itemMatchPageModificationSetups ?? Enumerable.Empty<ListItemMatchPageModificationSetup<ItemIdType>>().Materialize(); + ValidationPredicate = validationPredicate; + ValidationErrorNotifier = validationErrorNotifier; + } + } +} \ No newline at end of file
 
162
163
164
165
 
166
167
168
 
227
228
229
230
 
231
232
233
 
162
163
164
 
165
166
167
168
 
227
228
229
 
230
231
232
233
@@ -162,7 +162,7 @@
  private readonly List<Tuple<IEnumerable<ItemIdType>, bool, IEnumerable<System.Web.UI.WebControls.WebControl>>> displayLinks =   new List<Tuple<IEnumerable<ItemIdType>, bool, IEnumerable<System.Web.UI.WebControls.WebControl>>>();   - private FreeFormRadioList<ItemIdType> radioList; + private LegacyFreeFormRadioList<ItemIdType> radioList;   private EwfCheckBox firstRadioButton;   private FormValue<ItemIdType> formValue;   private System.Web.UI.WebControls.WebControl selectControl; @@ -227,7 +227,7 @@
    void ControlTreeDataLoader.LoadData() {   if( useHorizontalRadioLayout.HasValue ) { - radioList = FreeFormRadioList.Create( + radioList = LegacyFreeFormRadioList.Create(   items.Any( i => !i.IsValid ),   selectedItemId,   disableSingleButtonDetection: disableSingleRadioButtonDetection.Value,
 
211
212
213
214
215
216
217
 
 
 
 
 
218
219
220
 
211
212
213
 
 
 
 
214
215
216
217
218
219
220
221
@@ -211,10 +211,11 @@
  context.Id,   "setTimeout( function() { " + valueChangedAction.GetJsStatements() + " }, 0 );" )   : "", - isImprecise - ? ( (PageModificationValue<decimal>)pageModificationValue ).GetJsModificationStatements( "Number( $( this ).val() )" ) - : ( (PageModificationValue<decimal?>)pageModificationValue ).GetJsModificationStatements( "Number( $( this ).val() )" ) - .Surround( "$( '#{0}' ).change( function() {{ ".FormatWith( context.Id ), " } );" ), + ( isImprecise + ? ( (PageModificationValue<decimal>)pageModificationValue ).GetJsModificationStatements( "Number( $( this ).val() )" ) + : ( (PageModificationValue<decimal?>)pageModificationValue ).GetJsModificationStatements( "Number( $( this ).val() )" ) ).Surround( + "$( '#{0}' ).change( function() {{ ".FormatWith( context.Id ), + " } );" ),   autoCompleteStatements );     return new DisplayableElementLocalData(
 
10
11
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
14
15
 
66
67
68
69
 
70
71
72
 
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
 
193
194
195
 
196
197
198
199
@@ -10,6 +10,133 @@
  /// ID for the group. Otherwise use FreeFormRadioList.   /// </summary>   public class RadioButtonGroup { + internal static FormValue<ElementId> GetFormValue( + Func<IEnumerable<( ElementId id, bool isReadOnly, bool isSelected )>> buttonGetter, Func<ElementId, string> stringValueSelector, + Func<string, IEnumerable<ElementId>> selectedButtonIdInPostBackGetter, bool allowsNoSelection ) { + FormValue<ElementId> formValue = null; + return formValue = new FormValue<ElementId>( + () => buttonGetter().Where( i => i.isSelected ).Select( i => i.id ).FirstOrDefault(), + () => buttonGetter().Where( i => i.id.Id.Any() && !i.isReadOnly ).Select( i => i.id ).FirstOrDefault()?.Id ?? "", + stringValueSelector, + rawValue => { + if( rawValue != null ) { + var selectedButtonId = selectedButtonIdInPostBackGetter( rawValue ).SingleOrDefault(); + return selectedButtonId != null + ? PostBackValueValidationResult<ElementId>.CreateValid( selectedButtonId ) + : PostBackValueValidationResult<ElementId>.CreateInvalid(); + } + + var durableValue = formValue.GetDurableValue(); + if( durableValue != null ) { + var button = buttonGetter().Single( i => i.id == durableValue ); + if( !button.id.Id.Any() || button.isReadOnly ) + return PostBackValueValidationResult<ElementId>.CreateValid( durableValue ); + } + + return allowsNoSelection + ? PostBackValueValidationResult<ElementId>.CreateValid( null ) + : PostBackValueValidationResult<ElementId>.CreateInvalid(); + } ); + } + + internal static void ValidateControls( + bool allowsNoSelection, bool inNoSelectionState, IEnumerable<( ElementId id, bool isReadOnly, bool isSelected )> buttons, + bool disableSingleButtonDetection ) { + if( ( !allowsNoSelection || !inNoSelectionState ) && buttons.Count( i => i.isSelected ) != 1 ) + throw new ApplicationException( "If a radio button group is not in the no-selection state, then exactly one radio button must be selected." ); + + var activeButtons = buttons.Where( i => i.id.Id.Any() && !i.isReadOnly ).Materialize(); + if( activeButtons.Any() && !disableSingleButtonDetection && activeButtons.Count < 2 ) { + const string link = "http://developers.whatwg.org/states-of-the-type-attribute.html#radio-button-state-%28type=radio%29"; + throw new ApplicationException( "A radio button group must contain more than one element; see " + link + "." ); + } + } + + private readonly FormValue<ElementId> formValue; + + private readonly List<( ElementId id, bool isReadOnly, bool value, PageModificationValue<bool> pmv )> buttonIdAndIsReadOnlyAndValueAndPmvQuadruples = + new List<( ElementId, bool, bool, PageModificationValue<bool> )>(); + + private readonly FormAction selectionChangedAction; + + /// <summary> + /// Creates a radio button group. + /// </summary> + /// <param name="allowNoSelection">Pass true to allow the state in which none of the radio buttons are selected. Note that this is not recommended by the + /// Nielsen Norman Group; see http://www.nngroup.com/articles/checkboxes-vs-radio-buttons/ for more information.</param> + /// <param name="disableSingleButtonDetection">Pass true to allow just a single radio button to be displayed for this group. Use with caution, as this + /// violates the HTML specification.</param> + /// <param name="selectionChangedAction">The action that will occur when the selection is changed. Pass null for no action.</param> + public RadioButtonGroup( bool allowNoSelection, bool disableSingleButtonDetection = false, FormAction selectionChangedAction = null ) { + formValue = GetFormValue( + () => from i in buttonIdAndIsReadOnlyAndValueAndPmvQuadruples select ( i.id, i.isReadOnly, i.value ), + v => v?.Id ?? "", + rawValue => from quadruple in buttonIdAndIsReadOnlyAndValueAndPmvQuadruples + let id = quadruple.id + where id.Id.Any() && !quadruple.isReadOnly && id.Id == rawValue + select id, + allowNoSelection ); + + this.selectionChangedAction = selectionChangedAction; + + EwfPage.Instance.AddControlTreeValidation( + () => ValidateControls( + allowNoSelection, + buttonIdAndIsReadOnlyAndValueAndPmvQuadruples.All( i => !i.value ), + from i in buttonIdAndIsReadOnlyAndValueAndPmvQuadruples select ( i.id, i.isReadOnly, i.value ), + disableSingleButtonDetection ) ); + } + + /// <summary> + /// Creates a radio button that is part of the group. + /// </summary> + /// <param name="value"></param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the radio button.</param> + /// <param name="validationMethod">The validation method. Pass null if you’re only using this control for page modification.</param> + public Checkbox CreateRadioButton( + bool value, IReadOnlyCollection<PhrasingComponent> label, RadioButtonSetup setup = null, + Action<PostBackValue<bool>, Validator> validationMethod = null ) { + setup = setup ?? RadioButtonSetup.Create(); + + var id = new ElementId(); + formValue.AddPageModificationValue( setup.PageModificationValue, v => v == id ); + buttonIdAndIsReadOnlyAndValueAndPmvQuadruples.Add( ( id, setup.IsReadOnly, value, setup.PageModificationValue ) ); + + return new Checkbox( + formValue, + id, + setup, + label, + selectionChangedAction, + () => StringTools.ConcatenateWithDelimiter( + " ", + buttonIdAndIsReadOnlyAndValueAndPmvQuadruples.Select( i => i.pmv.GetJsModificationStatements( i.id == id ? "true" : "false" ) ).ToArray() ), + validationMethod != null + ? formValue.CreateValidation( + ( postBackValue, validator ) => validationMethod( + new PostBackValue<bool>( postBackValue.Value == id, postBackValue.ChangedOnPostBack ), + validator ) ) + : null ); + } + + /// <summary> + /// Creates a flow radio button that is part of the group. + /// </summary> + /// <param name="value"></param> + /// <param name="label">The radio button label. Do not pass null. Pass an empty collection for no label.</param> + /// <param name="setup">The setup object for the flow radio button.</param> + /// <param name="validationMethod">The validation method. Pass null if you’re only using the radio button for page modification.</param> + public FlowCheckbox CreateFlowRadioButton( + bool value, IReadOnlyCollection<PhrasingComponent> label, FlowRadioButtonSetup setup = null, + Action<PostBackValue<bool>, Validator> validationMethod = null ) { + setup = setup ?? FlowRadioButtonSetup.Create(); + return new FlowCheckbox( setup, CreateRadioButton( value, label, setup: setup.RadioButtonSetup, validationMethod: validationMethod ) ); + } + } + + [ Obsolete( "Guaranteed through 28 Feb 2019. Use RadioButtonGroup instead." ) ] + public class LegacyRadioButtonGroup {   internal static FormValue<CommonCheckBox> GetFormValue(   bool allowsNoSelection, Func<IEnumerable<CommonCheckBox>> allCheckBoxesGetter, Func<IEnumerable<CommonCheckBox>> checkedCheckBoxesGetter,   Func<CommonCheckBox, string> stringValueSelector, Func<string, IEnumerable<CommonCheckBox>> checkedCheckBoxesInPostBackGetter ) { @@ -66,7 +193,7 @@
  /// Nielsen Norman Group; see http://www.nngroup.com/articles/checkboxes-vs-radio-buttons/ for more information.</param>   /// <param name="disableSingleButtonDetection">Pass true to allow just a single radio button to be displayed for this group. Use with caution, as this   /// violates the HTML specification.</param> - public RadioButtonGroup( bool allowNoSelection, bool disableSingleButtonDetection = false ) { + public LegacyRadioButtonGroup( bool allowNoSelection, bool disableSingleButtonDetection = false ) {   formValue = GetFormValue(   allowNoSelection,   () => from i in checkBoxesAndSelectionStatesAndPageModificationValues select i.Item1,
 
3
4
5
6
7
8
9
10
11
12
 
 
 
13
14
15
 
3
4
5
 
 
 
 
 
 
 
6
7
8
9
10
11
@@ -3,13 +3,9 @@
   namespace EnterpriseWebLibrary.EnterpriseWebFramework {   public abstract class AutoCompleteService: EwfPage { - protected override EwfSafeResponseWriter responseWriter { - get { - return - new EwfSafeResponseWriter( - EwfResponse.Create( ContentTypes.PlainText, new EwfResponseBodyCreator( () => new JavaScriptSerializer().Serialize( getItems() ) ) ) ); - } - } + protected override EwfSafeRequestHandler requestHandler => + new EwfSafeResponseWriter( + EwfResponse.Create( ContentTypes.PlainText, new EwfResponseBodyCreator( () => new JavaScriptSerializer().Serialize( getItems() ) ) ) );     protected abstract IEnumerable<AutoCompleteItem> getItems();   }
 
1
 
 
 
2
3
4
 
30
31
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
 
 
1
2
3
4
5
6
 
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 
@@ -1,4 +1,6 @@
-using System.Collections.Generic; +using System; +using System.Collections.Generic; +using Humanizer;    namespace EnterpriseWebLibrary.EnterpriseWebFramework {   /// <summary> @@ -30,4 +32,24 @@
  return children;   }   } + + public static class GenericPhrasingContainerExtensionCreators { + /// <summary> + /// Creates a generic phrasing container (i.e. span element) that depends on this page-modification value. + /// </summary> + public static IReadOnlyCollection<PhrasingComponent> ToGenericPhrasingContainer<ModificationValueType>( + this PageModificationValue<ModificationValueType> pageModificationValue, Func<ModificationValueType, string> textSelector, + Func<string, string> jsTextExpressionGetter ) { + return new CustomPhrasingComponent( + new DisplayableElement( + context => { + pageModificationValue.AddJsModificationStatement( + valueExpression => "$( '#{0}' ).text( {1} );".FormatWith( context.Id, jsTextExpressionGetter( valueExpression ) ) ); + return new DisplayableElementData( + null, + () => new DisplayableElementLocalData( "span", focusDependentData: new DisplayableElementFocusDependentData( includeIdAttribute: true ) ), + children: new TextNode( () => textSelector( pageModificationValue.Value ) ).ToCollection() ); + } ).ToCollection() ).ToCollection(); + } + }  } \ No newline at end of file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
 
 
195
196
197
 
198
199
200
201
202
203
204
205
206
207
208
209
210
211
 
212
213
 
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
 
194
195
196
197
 
198
199
200
201
202
203
204
205
206
207
208
209
210
211
 
212
213
 
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
 using System;  using System.Collections.Generic;  using System.IO;  using System.Linq;  using System.Security.Cryptography;  using System.Text;  using System.Web;  using System.Web.UI;  using System.Web.UI.HtmlControls;  using System.Web.UI.WebControls;  using EnterpriseWebLibrary.Configuration;  using EnterpriseWebLibrary.DataAccess;  using EnterpriseWebLibrary.EnterpriseWebFramework.DisplayLinking;  using EnterpriseWebLibrary.EnterpriseWebFramework.UserManagement;  using EnterpriseWebLibrary.WebSessionState;  using Humanizer;  using NodaTime;  using StackExchange.Profiling;    namespace EnterpriseWebLibrary.EnterpriseWebFramework {   /// <summary>   /// A System.Web.UI.Page that contains special Red Stapler Enterprise Web Framework logic. Requires that view state and session state be enabled.   /// </summary>   public abstract class EwfPage: Page {   // This string is duplicated in the JavaScript file.   private const string postBackHiddenFieldName = "ewfPostBack";     internal const string ButtonElementName = "ewfButton";     private static Func<IEnumerable<EtherealComponent>> browsingModalBoxCreator;   private static Func<IEnumerable<ResourceInfo>> cssInfoCreator;     internal new static void Init( Func<IEnumerable<EtherealComponent>> browsingModalBoxCreator, Func<IEnumerable<ResourceInfo>> cssInfoCreator ) {   EwfValidation.Init(   () => Instance.formState.ValidationPredicate,   () => Instance.formState.DataModifications,   () => Instance.formState.DataModificationsWithValidationsFromOtherElements,   () => Instance.formState.ReportValidationCreated() );   PostBack.Init( () => Instance.formState.DataModifications );   PostBackFormAction.Init(   postBack => {   if( !Instance.postBacksById.TryGetValue( postBack.Id, out var existingPostBack ) )   Instance.postBacksById.Add( postBack.Id, postBack );   else if( existingPostBack != postBack )   throw new ApplicationException( "A post-back with an ID of \"{0}\" already exists in the page.".FormatWith( existingPostBack.Id ) );   },   postBack => {   if( Instance.GetPostBack( postBack.Id ) != postBack )   throw new ApplicationException( "The post-back must have been added to the page." );   if( ( postBack as ActionPostBack )?.ValidationDm is PostBack validationPostBack &&   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." );   } );   FormState.Init(   () => Instance.formState,   dataModifications => {   if( dataModifications.Contains( Instance.dataUpdate ) &&   dataModifications.Any( i => i != Instance.dataUpdate && !( (ActionPostBack)i ).IsIntermediate ) )   throw new ApplicationException(   "If the data-update modification is included, it is meaningless to include any full post-backs since these inherently update the page's data." );   },   dataModification => dataModification == Instance.dataUpdate ? Instance.dataUpdatePostBack : (ActionPostBack)dataModification );   EwfPage.browsingModalBoxCreator = browsingModalBoxCreator;   EwfPage.cssInfoCreator = cssInfoCreator;   }     /// <summary>   /// Returns the currently executing EwfPage, or null if the currently executing page is not an EwfPage.   /// </summary>   public static EwfPage Instance => HttpContext.Current.CurrentHandler as EwfPage;     /// <summary>   /// Add a status message of the given type to the status message collection.   /// </summary>   public static void AddStatusMessage( StatusMessageType type, string message ) {   Instance.statusMessages.Add( new Tuple<StatusMessageType, string>( type, message ) );   }     internal static void AssertPageTreeNotBuilt() {   if( Instance.formState == null )   throw new ApplicationException( "The page tree has already been built." );   }     internal static void AssertPageTreeBuilt() {   if( Instance.formState != null )   throw new ApplicationException( "The page tree has not yet been built." );   }     private Control contentContainer;   private Control etherealPlace;   private FormState formState;   internal readonly ModalBoxId BrowsingModalBoxId = new ModalBoxId();   private readonly BasicDataModification dataUpdate = new BasicDataModification();   private readonly PostBack dataUpdatePostBack = PostBack.CreateDataUpdate();     internal readonly Dictionary<PageComponent, IReadOnlyCollection<Control>> ControlsByComponent =   new Dictionary<PageComponent, IReadOnlyCollection<Control>>();     private readonly Dictionary<Control, List<EtherealControl>> etherealControlsByControl = new Dictionary<Control, List<EtherealControl>>();   private readonly Dictionary<string, PostBack> postBacksById = new Dictionary<string, PostBack>();   private readonly List<FormValue> formValues = new List<FormValue>();   private readonly List<DisplayLink> displayLinks = new List<DisplayLink>();   private readonly List<LegacyUpdateRegionLinker> updateRegionLinkers = new List<LegacyUpdateRegionLinker>();   private readonly Dictionary<EwfValidation, List<string>> modErrorDisplaysByValidation = new Dictionary<EwfValidation, List<string>>();   internal readonly HashSet<EwfValidation> ValidationsWithErrors = new HashSet<EwfValidation>();   internal readonly Dictionary<Control, List<AutofocusCondition>> AutofocusConditionsByControl = new Dictionary<Control, List<AutofocusCondition>>();   private readonly List<Action> controlTreeValidations = new List<Action>();   internal PostBack SubmitButtonPostBack;   private readonly List<Tuple<StatusMessageType, string>> statusMessages = new List<Tuple<StatusMessageType, string>>();     /// <summary>   /// Returns the entity setup for this page, if one exists.   /// </summary>   public abstract EntitySetupBase EsAsBaseType { get; }     /// <summary>   /// Gets the page info object for this page. Necessary so we can validate query parameters and ensure authenticated user can access the page.   /// </summary>   public abstract PageInfo InfoAsBaseType { get; }     /// <summary>   /// Gets the parameters modification object for this page.   /// </summary>   public abstract ParametersModificationBase ParametersModificationAsBaseType { get; }     /// <summary>   /// Gets the page state for this page.   /// </summary>   public PageState PageState => AppRequestState.Instance.EwfPageRequestState.PageState;     /// <summary>   /// Creates a new page. Do not call this yourself.   /// </summary>   protected EwfPage() {   // Use the entire page as the default content container.   contentContainer = this;     // We suspect that this disables browser detection for the entire request, not just the page.   ClientTarget = "uplevel";   }     /// <summary>   /// Executes EWF logic in addition to the standard ASP.NET PreInit logic.   /// </summary>   protected sealed override void OnPreInit( EventArgs e ) {   // This logic should happen before the page gets the PreInit event in case it wants to determine the master based on parameters.   // NOTE: If the entity setup is a master page, we need to delay this call until after PreInit.   initEntitySetupAndCreateInfoObjects();     base.OnPreInit( e );   }     private void initEntitySetupAndCreateInfoObjects() {   AppRequestState.Instance.UserDisabledByPage = true;   try {   initEntitySetup();   if( EsAsBaseType != null )   using( MiniProfiler.Current.Step( "EWF - Create entity-setup info" ) )   EsAsBaseType.CreateInfoFromQueryString();   using( MiniProfiler.Current.Step( "EWF - Create page info" ) )   createInfoFromQueryString();     // If the request doesn't match the page's specified security level, redirect with the proper level. Do this before ensuring that the user can access the   // page since in certificate authentication systems this can be affected by the connection security level.   //   // When goal 448 (Clean URLs) is complete, we want to do full URL normalization during request dispatching, like we do with shortcut URLs. We probably   // should only do this on GET requests since we don't want to wipe out post backs.   bool connectionSecurityIncorrect;   using( MiniProfiler.Current.Step( "EWF - Check connection security" ) )   connectionSecurityIncorrect = getConnectionSecurityIncorrect();   if( connectionSecurityIncorrect )   NetTools.Redirect( InfoAsBaseType.GetUrl( false, false, true ) );   }   finally {   AppRequestState.Instance.UserDisabledByPage = false;   }     // This logic depends on the authenticated user and on page and entity setup info objects.   bool userCanAccessResource;   using( MiniProfiler.Current.Step( "EWF - Check page authorization" ) )   userCanAccessResource = InfoAsBaseType.UserCanAccessResource;   if( !userCanAccessResource )   throw new AccessDeniedException(   ConfigurationStatics.IsIntermediateInstallation && !InfoAsBaseType.IsIntermediateInstallationPublicResource &&   !AppRequestState.Instance.IntermediateUserExists,   InfoAsBaseType.LogInPage );     DisabledResourceMode disabledMode;   using( MiniProfiler.Current.Step( "EWF - Check alternative page mode" ) )   disabledMode = InfoAsBaseType.AlternativeMode as DisabledResourceMode;   if( disabledMode != null )   throw new PageDisabledException( disabledMode.Message );   - if( responseWriter != null ) { + var cachedRequestHandler = requestHandler; + if( cachedRequestHandler != null ) {   Response.ClearHeaders();   Response.ClearContent(); - responseWriter.WriteResponse(); + cachedRequestHandler.WriteResponse();     // Calling Response.End() is not a good practice; see http://stackoverflow.com/q/1087777/35349. We should be able to remove this call when we separate   // EWF from Web Forms. This is EnduraCode goal 790.   Response.End();   }   }     /// <summary>   /// Loads the entity display setup for the page, if one exists.   /// </summary>   protected abstract void initEntitySetup();     /// <summary> - /// Gets the response writer for this page. NOTE: We should re-implement this such that the classes that override this are plain old HTTP handlers instead of pages. + /// Gets the request handler for this page, which will override the page.   /// </summary> - protected virtual EwfSafeResponseWriter responseWriter { get { return null; } } + protected virtual EwfSafeRequestHandler requestHandler => null;     /// <summary>   /// Performs EWF activities in addition to the normal InitComplete activities.   /// </summary>   protected sealed override void OnInitComplete( EventArgs e ) {   base.OnInitComplete( e );   if( IsPostBack )   return;     if( AppRequestState.Instance.EwfPageRequestState != null )   PageState.ClearCustomStateControlKeys();   else if( StandardLibrarySessionState.Instance.EwfPageRequestState != null ) {   AppRequestState.Instance.EwfPageRequestState = StandardLibrarySessionState.Instance.EwfPageRequestState;   StandardLibrarySessionState.Instance.EwfPageRequestState = null;   PageState.ClearCustomStateControlKeys();   }   else   AppRequestState.Instance.EwfPageRequestState = new EwfPageRequestState( PageState.CreateForNewPage(), null, null );     var requestState = AppRequestState.Instance.EwfPageRequestState;   var dmIdAndSecondaryOp = requestState.DmIdAndSecondaryOp;     // Page-view data modifications. All data modifications that happen simply because of a request and require no other action by the user should happen once   // per page view, and prior to LoadData so that the modified data can be used in the page if necessary.   if( requestState.StaticRegionContents == null || ( !requestState.ModificationErrorsExist && dmIdAndSecondaryOp != null &&   new[] { SecondaryPostBackOperation.Validate, SecondaryPostBackOperation.ValidateChangesOnly }.Contains(   dmIdAndSecondaryOp.Item2 ) ) ) {   var modMethods = new List<Action>();   modMethods.Add( EwfApp.Instance.GetPageViewDataModificationMethod() );   if( AppRequestState.Instance.UserAccessible ) {   if( AppTools.User != null )   modMethods.Add( getLastPageRequestTimeUpdateMethod( AppTools.User ) );   if( AppRequestState.Instance.ImpersonatorExists && AppRequestState.Instance.ImpersonatorUser != null )   modMethods.Add( getLastPageRequestTimeUpdateMethod( AppRequestState.Instance.ImpersonatorUser ) );   }   modMethods.Add( getPageViewDataModificationMethod() );   modMethods = modMethods.Where( i => i != null ).ToList();     if( modMethods.Any() ) {   DataAccessState.Current.DisableCache();   try {   foreach( var i in modMethods )   i();   AppRequestState.AddNonTransactionalModificationMethod(   () => {   StandardLibrarySessionState.Instance.StatusMessages.AddRange( statusMessages );   statusMessages.Clear();   } );   AppRequestState.Instance.CommitDatabaseTransactionsAndExecuteNonTransactionalModificationMethods();   }   finally {   DataAccessState.Current.ResetCache();   }   }     // Re-create info objects. A big reason to do this is that some info objects execute database queries or other code in order to prime the data-access   // cache. The code above resets the cache and we want to re-prime it right away.   EsAsBaseType?.ClearInfo();   clearInfo();   AppRequestState.Instance.UserDisabledByPage = true;   try {   if( EsAsBaseType != null )   using( MiniProfiler.Current.Step( "EWF - Create entity-setup info after page-view data modifications" ) )   EsAsBaseType.CreateInfoFromQueryString();   using( MiniProfiler.Current.Step( "EWF - Create page info after page-view data modifications" ) )   createInfoFromQueryString();     bool connectionSecurityIncorrect;   using( MiniProfiler.Current.Step( "EWF - Check connection security after page-view data modifications" ) )   connectionSecurityIncorrect = getConnectionSecurityIncorrect();   if( connectionSecurityIncorrect )   throw getPossibleDeveloperMistakeException( "The connection security of the page changed after page-view data modifications." );   }   finally {   AppRequestState.Instance.UserDisabledByPage = false;   }   bool userCanAccessResource;   using( MiniProfiler.Current.Step( "EWF - Check page authorization after page-view data modifications" ) )   userCanAccessResource = InfoAsBaseType.UserCanAccessResource;   DisabledResourceMode disabledMode;   using( MiniProfiler.Current.Step( "EWF - Check alternative page mode after page-view data modifications" ) )   disabledMode = InfoAsBaseType.AlternativeMode as DisabledResourceMode;   if( !userCanAccessResource || disabledMode != null )   throw getPossibleDeveloperMistakeException( "The user lost access to the page or the page became disabled after page-view data modifications." );   }     onLoadData();     if( requestState.StaticRegionContents != null ) {   var updateRegionLinkersByKey = updateRegionLinkers.ToDictionary( i => i.Key );   var updateRegionControls = requestState.UpdateRegionKeysAndArguments.SelectMany(   keyAndArg => {   LegacyUpdateRegionLinker linker;   if( !updateRegionLinkersByKey.TryGetValue( keyAndArg.Item1, out linker ) )   throw getPossibleDeveloperMistakeException( "An update region linker with the key \"{0}\" does not exist.".FormatWith( keyAndArg.Item1 ) );   return linker.PostModificationRegionGetter( keyAndArg.Item2 );   } );     var staticRegionContents = getStaticRegionContents( updateRegionControls );   if( staticRegionContents.Item1 != requestState.StaticRegionContents ||   formValues.Any( i => i.GetPostBackValueKey().Any() && i.PostBackValueIsInvalid( requestState.PostBackValues ) ) )   throw getPossibleDeveloperMistakeException(   requestState.ModificationErrorsExist   ?   "Form controls, modification-error-display keys, and post-back IDs may not change if modification errors exist." +   " (IMPORTANT: This exception may have been thrown because EWL Goal 588 hasn't been completed. See the note in the goal about the EwfPage bug and disregard the rest of this error message.)"   : new[] { SecondaryPostBackOperation.Validate, SecondaryPostBackOperation.ValidateChangesOnly }.Contains( dmIdAndSecondaryOp.Item2 )   ? "Form controls outside of update regions may not change on an intermediate post-back."   : "Form controls and post-back IDs may not change during the validation stage of an intermediate post-back." );   }     if( !requestState.ModificationErrorsExist && dmIdAndSecondaryOp != null && dmIdAndSecondaryOp.Item2 == SecondaryPostBackOperation.Validate ) {   var secondaryDm = dmIdAndSecondaryOp.Item1.Any() ? GetPostBack( dmIdAndSecondaryOp.Item1 ) as DataModification : dataUpdate;   if( secondaryDm == null )   throw getPossibleDeveloperMistakeException( "A data modification with an ID of \"{0}\" does not exist.".FormatWith( dmIdAndSecondaryOp.Item1 ) );     var navigationNeeded = true;   executeWithDataModificationExceptionHandling(   () => {   if( secondaryDm == dataUpdate )   navigationNeeded = dataUpdate.Execute(   true,   formValues.Any( i => i.ValueChangedOnPostBack( requestState.PostBackValues ) ),   handleValidationErrors,   performValidationOnly: true );   else {   var formValuesChanged = GetDescendants( contentContainer )   .OfType<FormValueControl>()   .Any( i => i.FormValue != null && i.FormValue.ValueChangedOnPostBack( requestState.PostBackValues ) );   navigationNeeded = ( (ActionPostBack)secondaryDm ).Execute( formValuesChanged, handleValidationErrors, null );   }     if( navigationNeeded ) {   requestState.DmIdAndSecondaryOp = Tuple.Create( dmIdAndSecondaryOp.Item1, SecondaryPostBackOperation.NoOperation );   requestState.SetStaticAndUpdateRegionState( getStaticRegionContents( new Control[ 0 ] ).Item1, new Tuple<string, string>[ 0 ] );   }   } );   if( navigationNeeded )   navigate( null, null );   }   }     /// <summary>   /// It's important to call this from EwfPage instead of EwfApp because requests for some pages, with their associated images, CSS files, etc., can easily   /// cause 20-30 server requests, and we only want to update the time stamp once for all of these.   /// </summary>   private Action getLastPageRequestTimeUpdateMethod( User user ) {   // Only update the request time if a significant amount of time has passed since we did it last. This can dramatically reduce concurrency issues caused by   // people rapidly assigning tasks to one another in the System Manager or similar situations.   if( AppRequestState.RequestTime - user.LastRequestTime < Duration.FromMinutes( 60 ) )   return null;     // Now we want to do a timestamp-based concurrency check so we don't update the last login date if we know another transaction already did.   // It is not perfect, but it reduces errors caused by one user doing a long-running request and then doing smaller requests   // in another browser window while the first one is still running.   // We have to query in a separate transaction because otherwise snapshot isolation will result in us always getting the original LastRequestTime, even if   // another transaction has modified its value during this transaction.   var newlyQueriedUser = new DataAccessState().ExecuteWithThis(   () => {   Func<User> userGetter = () => UserManagementStatics.GetUser( user.UserId, false );   return ConfigurationStatics.DatabaseExists ? DataAccessState.Current.PrimaryDatabaseConnection.ExecuteWithConnectionOpen( userGetter ) : userGetter();   } );   if( newlyQueriedUser == null || newlyQueriedUser.LastRequestTime > user.LastRequestTime )   return null;     return () => {   Action userUpdater = () => {   if( FormsAuthStatics.FormsAuthEnabled ) {   var formsAuthCapableUser = (FormsAuthCapableUser)user;   FormsAuthStatics.SystemProvider.InsertOrUpdateUser(   user.UserId,   user.Email,   user.Role.RoleId,   AppRequestState.RequestTime,   formsAuthCapableUser.Salt,   formsAuthCapableUser.SaltedPassword,   formsAuthCapableUser.MustChangePassword );   }   else   ( UserManagementStatics.SystemProvider as ExternalAuthUserManagementProvider )?.InsertOrUpdateUser(   user.UserId,   user.Email,   user.Role.RoleId,   AppRequestState.RequestTime );   };   if( ConfigurationStatics.DatabaseExists )   DataAccessState.Current.PrimaryDatabaseConnection.ExecuteInTransaction(   () => {   try {   userUpdater();   }   catch( DbConcurrencyException ) {   // Since this method is called on every page request, concurrency errors are common. They are caused when an authenticated user makes one request   // and then makes another before ASP.NET has finished processing the first. Since we are only updating the last request date and time, we don't   // need to get an error email if the update fails.   throw new DoNotCommitException();   }   } );   else   userUpdater();   };   }     // The warning below also appears on EwfApp.GetPageViewDataModificationMethod.   /// <summary>   /// Returns a method that executes data modifications that happen simply because of a request and require no other action by the user. Returns null if there   /// are no modifications, which can improve page performance since the data-access cache does not need to be reset.   ///   /// WARNING: Don't ever use this to correct for missing loadData preconditions. For example, do not create a page that requires a user preferences row to   /// exist and then use a page-view data modification to create the row if it is missing. Page-view data modifications will not execute before the first   /// loadData call on post-back requests, and we provide no mechanism to do this because it would allow developers to accidentally cause false user   /// concurrency errors by modifying data that affects the rendering of the page.   /// </summary>   protected virtual Action getPageViewDataModificationMethod() {   return null;   }     /// <summary>   /// EWF use only.   /// </summary>   protected abstract void clearInfo();     /// <summary>   /// Creates the info object for this page based on the query parameters of the request.   /// </summary>   protected abstract void createInfoFromQueryString();     private bool getConnectionSecurityIncorrect() {   return InfoAsBaseType.ShouldBeSecureGivenCurrentRequest != EwfApp.Instance.RequestIsSecure( Request );   }     /// <summary>   /// Loads hidden field state. We use this instead of LoadViewState because the latter doesn't get called during post backs on which the page structure   /// changes.   /// </summary>   protected sealed override object LoadPageStateFromPersistenceMedium() {   string formValueHash = null;   string lastPostBackFailingDmId = null;   try {   // Based on our implementation of SavePageStateToPersistenceMedium, the base implementation of LoadPageStateFromPersistenceMedium will return a Pair   // with no First object.   var pair = base.LoadPageStateFromPersistenceMedium() as Pair;     var savedState = PageState.CreateFromViewState( (object[])pair.Second );   AppRequestState.Instance.EwfPageRequestState = new EwfPageRequestState(   savedState.Item1,   Request.Form[ "__SCROLLPOSITIONX" ],   Request.Form[ "__SCROLLPOSITIONY" ] );   formValueHash = (string)savedState.Item2[ 0 ];   lastPostBackFailingDmId = (string)savedState.Item2[ 1 ];   }   catch {   // Set a 400 status code if there are any problems loading hidden field state. We're assuming these problems are never the developers' fault.   if( AppRequestState.Instance.EwfPageRequestState == null )   AppRequestState.Instance.EwfPageRequestState = new EwfPageRequestState( PageState.CreateForNewPage(), null, null );   Response.StatusCode = 400;   Response.TrySkipIisCustomErrors = true;   AppRequestState.Instance.EwfPageRequestState.FocusKey = "";   AppRequestState.Instance.EwfPageRequestState.GeneralModificationErrors =   Translation.ApplicationHasBeenUpdatedAndWeCouldNotInterpretAction.ToCollection();   resetPage();   }     onLoadData();     var requestState = AppRequestState.Instance.EwfPageRequestState;   ResourceInfo redirectInfo = null;   FullResponse fullSecondaryResponse = null;   executeWithDataModificationExceptionHandling(   () => {   validateFormSubmission( formValueHash );     // Get the post-back object and, if necessary, the last post-back's failing data modification.   var postBackId = Request.Form[ postBackHiddenFieldName ]; // returns null if field missing   var postBack = postBackId != null ? GetPostBack( postBackId ) : null;   if( postBack == null )   throw new DataModific