[Test] // bug #82546 public void FindControl_NamingContainer() { Control topControl = new NamingContainer(); topControl.ID = "top"; Control controlLevel1A = new Control(); controlLevel1A.ID = "Level1#A"; topControl.Controls.Add(controlLevel1A); Control controlLevel1B = new Control(); controlLevel1B.ID = "Level1#B"; topControl.Controls.Add(controlLevel1B); Control controlLevel2AA = new Control(); controlLevel2AA.ID = "Level2#AA"; controlLevel1A.Controls.Add(controlLevel2AA); Control controlLevel2AB = new Control(); controlLevel2AB.ID = "Level2#AB"; controlLevel1A.Controls.Add(controlLevel2AB); Control foundControl = topControl.FindControl("Level1#A"); Assert.IsNotNull(foundControl, "#A1"); Assert.AreSame(controlLevel1A, foundControl, "#A2"); foundControl = topControl.FindControl("LEVEL1#B"); Assert.IsNotNull(foundControl, "#B1"); Assert.AreSame(controlLevel1B, foundControl, "#B2"); foundControl = topControl.FindControl("LeVeL2#AB"); Assert.IsNotNull(foundControl, "#C1"); Assert.AreSame(controlLevel2AB, foundControl, "#C2"); foundControl = topControl.FindControl("doesnotexist"); Assert.IsNull(foundControl, "#D1"); foundControl = topControl.FindControl("top"); Assert.IsNull(foundControl, "#D2"); foundControl = controlLevel1A.FindControl("Level2#AA"); Assert.IsNotNull(foundControl, "#E1"); Assert.AreSame(controlLevel2AA, foundControl, "#E2"); foundControl = controlLevel1A.FindControl("LEveL2#ab"); Assert.IsNotNull(foundControl, "#F1"); Assert.AreSame(controlLevel2AB, foundControl, "#F2"); }
/// <summary> /// Sets the validation value of the control named relative to the validator. /// </summary> /// <param name="name"></param> /// <param name="value"></param> protected virtual void SetControlValidationValue(string name, string value) { // get the control using the relative name Control control = NamingContainer.FindControl(name); if (control == null) { return; } if (control is IEditableTextControl) { ((IEditableTextControl)control).Text = value; } else { // get its validation property PropertyDescriptor prop = GetValidationProperty(control); if (prop == null) { return; } // get its value as a string object currentValue = prop.GetValue(control); if (currentValue is ListItem) { ((ListItem)currentValue).Value = value; } } }
protected override void CreateChildValidators() { if (this.Site != null && this.Site.DesignMode) { return; } BocTextValue textValueControl = NamingContainer.FindControl(ControlToValidate) as BocTextValue; if (textValueControl == null) { return; } if (textValueControl.IsReadOnly) { return; } string baseID = this.ID + "_Validator"; foreach (BaseValidator validator in CreateValidators(textValueControl, baseID)) { Controls.Add(validator); } }
private string GetClientIDsAsJSArray(string idsString) { ArrayList ids = new ArrayList(); // IDs of buttons listed in idsString if (idsString != null) { ids.AddRange(idsString.Split(' ')); } ArrayList clientIDs = new ArrayList(); foreach (string id in ids) { Control c = NamingContainer.FindControl(id); if (c != null) { clientIDs.Add(c.ClientID); } else { // If we couldn't find a control with that ID, it might be a client-side-only element. // In that case assume that the ID that was specified is already the Client ID. clientIDs.Add(id); } } if (clientIDs.Count == 0) { return("[]"); } return("['" + String.Join("','", (string[])clientIDs.ToArray(typeof(string))) + "']"); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { _saveButton = NamingContainer.FindControl(SaveButtonID) as Button; _deleteButton = NamingContainer.FindControl(DeleteButtonID) as Button; _contentTitle = NamingContainer.FindControl(ContentTitleID) as Label; _noticeMessage = NamingContainer.FindControl(NoticeMessageID) as NoticeLabel; if (_saveButton != null) { InitSaveButton(); } if (_deleteButton != null) { _deleteButton.Click += DeleteButton_Click; GetRequestObject(); } } catch (WebControlException ex) { AddWarning(ex.RelatedControl, ex.Message); } catch (Exception ex) { AddWarning(ex.Message); } }
private TextBox GetTextBoxToValidate() { if (string.IsNullOrEmpty(ControlToValidate)) { throw new ApplicationException("The ControlToValidate property has not been set for the '" + UniqueID + "' " + GetType().Name + "."); } Control control = NamingContainer.FindControl(ControlToValidate); if (control == null) { throw new ApplicationException("The control to validate, '" + ControlToValidate + "', could not be found."); } TextBox textBox = control as TextBox; if (textBox == null) { if (control is HtmlTextArea) { throw new ApplicationException("The control to validate, '" + ControlToValidate + "', is a server-side <textarea> - it must be a TextBox instead."); } else { throw new ApplicationException("The control to validate, '" + ControlToValidate + "', is not a TextBox."); } } return(textBox); }
protected override bool EvaluateIsValid() { var control = NamingContainer.FindControl(ControlToValidate); var autoCompleteReferenceValue = control as BocAutoCompleteReferenceValue; if (autoCompleteReferenceValue == null) { throw new InvalidOperationException( "BocAutoCompleteReferenceValueInvalidDisplayNameValidator may only be applied to controls of type BocAutoCompleteReferenceValue"); } var validationValue = GetControlValidationValue(ControlToValidate); if (string.IsNullOrEmpty(validationValue)) { return(true); } var validationValueParts = validationValue.Split(new[] { '\n' }, StringSplitOptions.None); if (validationValueParts.Length != 2) { throw new InvalidOperationException( string.Format("ValidationValue for control '{0}' has an invalid format.", ControlToValidate)); } if (string.IsNullOrEmpty(validationValueParts[0]) && !string.IsNullOrEmpty(validationValueParts[1])) { return(false); } return(true); }
protected override bool EvaluateIsValid() { string controlValue = GetControlValidationValue(ControlToValidate); if (controlValue == null || controlValue.Trim().Length == 0) { return(true); } try { Match m = Regex.Match(controlValue, ValidationExpression); var result = (m.Success && m.Index == 0 && m.Length == controlValue.Length); //Check to see if validation failed, if it did, add the class to the control to validate if (!result) { var control = (WebControl)NamingContainer.FindControl(ControlToValidate); if (!control.CssClass.Contains(CssControlErrorClass)) { control.CssClass += " " + CssControlErrorClass; } } return(result); } catch { return(true); } }
/// <devdoc> /// <para>Evaluates validity and updates the <see cref='System.Web.UI.WebControls.BaseValidator.IsValid'/> property.</para> /// </devdoc> public void Validate() { IsValid = true; if (!Visible || !Enabled) { return; } propertiesChecked = false; if (!PropertiesValid) { return; } IsValid = EvaluateIsValid(); Debug.Trace("BaseValidator.Validate", "id:" + ID + ", evaluateIsValid = " + IsValid.ToString()); if (!IsValid) { Page page = Page; if (page != null && SetFocusOnError) { // Dev10 584609 Need to render ClientID not control id for auto focus to work string validateId = ControlToValidate; Control c = NamingContainer.FindControl(validateId); if (c != null) { validateId = c.ClientID; } Page.SetValidatorInvalidControlFocus(validateId); } } }
private DataSourceView GetDataSourceView() { var dataSource = DataSource ?? (IDataSource)Parent.FindControl(DataSourceID); if (dataSource == null && namingContainerIDOnInit != NamingContainer.ID) { var container = NamingContainer.FindControl(namingContainerIDOnInit); if (container != null) { dataSource = (IDataSource)container.FindControl(DataSourceID); } } if (dataSource == null) { throw new Exception("DataSource not found"); } var dataSourceView = dataSource.GetView("default"); if (dataSourceView == null) { throw new Exception("DataSourceView not found"); } return(dataSourceView); }
protected override bool EvaluateIsValid() { //Default implementation of the RegularExpressionFieldvalidator string controlValue = GetControlValidationValue(ControlToValidate); if (controlValue == null || controlValue.Trim().Length == 0) { return(true); } try { Match m = Regex.Match(controlValue, ValidationExpression); var result = (m.Success && m.Index == 0 && m.Length == controlValue.Length); //Check to see if validation failed, if it did, add the class to the control to validate if (!result) { var control = (WebControl)NamingContainer.FindControl(ControlToValidate); //Didn't look into it too much, but the validators fire twice for some reason if (!control.CssClass.Contains(CssControlErrorClass)) { control.CssClass += " " + CssControlErrorClass; } } return(result); } catch { return(true); } }
protected override void CreateChildControls() { Controls.Clear(); if (string.IsNullOrEmpty(ControlToValidate)) { throw new ArgumentNullException("ControlToValidate"); } WebControl control = (WebControl)NamingContainer.FindControl(ControlToValidate); if ((control != null) && (Validators.Count > 0)) { targetClientId = control.ClientID; if (!(control is RadioButtonList)) { control.Attributes.Add("ValidateGroup", ValidateGroup); } if (!string.IsNullOrEmpty(ContainerId)) { ValidatorContainer container = (ValidatorContainer)Page.FindControl(ContainerId); if (container == null) { container = FindFromMasterPage(); } if (container == null) { throw new Exception(string.Format(CultureInfo.InvariantCulture, "The validator container: '{0}' was not found", new object[] { ContainerId })); } CreateToContainer(container); } else { CreateToChilds(); } } }
/// <summary> /// Gets the control validation value. /// </summary> /// <remarks> /// Based on the reflected source of <see cref="BaseValidator.GetControlValidationValue"/>. /// </remarks> /// <param name="name">The name.</param> /// <returns></returns> private string GetControlValidationValue(string name) { Control valueControl = NamingContainer.FindControl(name); if (valueControl == null) { return(null); } PropertyDescriptor validationProperty = BaseValidator.GetValidationProperty(valueControl); if (validationProperty == null) { return(null); } object value = validationProperty.GetValue(valueControl); if (value is ListItem) { return(((ListItem)value).Value); } if (value != null) { return(value.ToString()); } return(String.Empty); }
/// <summary> /// Save any values in the TargetProperties objects out to client state so they are available /// on the client side. /// </summary> private void SaveClientStateValues() { if (EnableClientState) { HiddenField hiddenField = null; // if we don't have a value here, this properties // object may have been created dynamically in code // so we create the field on demand. // if (string.IsNullOrEmpty(ClientStateFieldID)) { hiddenField = CreateClientStateField(); } else { hiddenField = (HiddenField)NamingContainer.FindControl(ClientStateFieldID); } if (hiddenField != null) { hiddenField.Value = ClientState; } } }
public string GetText() { if (!string.IsNullOrEmpty(_text)) { return(_text); } string forControlBackUp = ForControl; ForControl = ForControl ?? string.Empty; string text = string.Empty; if (ForControl == string.Empty) { text = "[Label]"; } else { ISmartControl smartControl = NamingContainer.FindControl(ForControl) as ISmartControl; if (smartControl != null && smartControl.DisplayName != null) { text = smartControl.DisplayName; } else { text = "[Label for " + ForControl + "]"; } } ForControl = forControlBackUp; return(text); }
private void RenderLabelElement(HtmlTextWriter writer) { writer.WriteBeginTag("label"); if (ForControl.Length > 0) { Control c = NamingContainer.FindControl(ForControl); if (c != null) { writer.WriteAttribute("for", c.ClientID); } } if (CssClass.Length > 0) { writer.WriteAttribute("class", CssClass); } writer.Write(HtmlTextWriter.TagRightChar); if ((ConfigKey != "EmptyLabel") && (ConfigKey != "spacer")) { string text = HttpContext.GetGlobalResourceObject(ResourceFile, ConfigKey) as string; if (text == null) { text = ShowWarningOnMissingKey ? string.Format("{0} not found in {1}.resx file", ConfigKey, ResourceFile) : ConfigKey; } // should we be html encoding here? writer.WriteEncodedText(text); } writer.WriteEndTag("label"); }
protected string GetControlValidationValue(string name) { Control control = NamingContainer.FindControl(name); if (control == null) { return(null); } PropertyDescriptor prop = BaseValidator.GetValidationProperty(control); if (prop == null) { return(null); } object o = prop.GetValue(control); if (o == null) { return(String.Empty); } if (o is ListItem) { return(((ListItem)o).Value); } return(o.ToString()); }
protected override void Render(HtmlTextWriter writer) { if (this.Site != null && this.Site.DesignMode) { this.ForeColor = System.Drawing.Color.Red; this.RenderBeginTag(writer); writer.Write("[" + this.GetType().Name + " for " + ControlToValidate + "]"); this.RenderEndTag(writer); return; } Control controlToValidate = NamingContainer.FindControl(ControlToValidate); if (controlToValidate == null) { return; } if (!_targetControlType.IsAssignableFrom(controlToValidate.GetType())) { writer.Write("<b>" + this.GetType().Name + " '" + this.ID + "': ControlToValidate must be a " + _targetControlType + " control.</b>"); return; } this.RenderBeginTag(writer); RenderChildren(writer); this.RenderEndTag(writer); }
protected string GetControlValidationValue(string name) { Control component = NamingContainer.FindControl(name); if (component == null) { return(null); } PropertyDescriptor validationProperty = GetValidationProperty(component); if (validationProperty == null) { return(null); } object obj2 = validationProperty.GetValue(component); if (obj2 is ListItem) { return(((ListItem)obj2).Value); } if (obj2 != null) { return(obj2.ToString()); } return(string.Empty); }
/// <devdoc> /// <para> Gets the validation value of the control /// named relative to the validator.</para> /// </devdoc> protected string GetControlValidationValue(string name) { // get the control using the relative name Control c = NamingContainer.FindControl(name); if (c == null) { return(null); } // get its validation property PropertyDescriptor prop = GetValidationProperty(c); if (prop == null) { return(null); } // get its value as a string object value = prop.GetValue(c); if (value is ListItem) { return(((ListItem)value).Value); } else if (value != null) { return(value.ToString()); } else { return(string.Empty); } }
/// <summary> /// Called during the validation stage when ASP.NET processes a Web Form. /// </summary> /// <returns>true if the value in the input control is valid; otherwise, false.</returns> protected override bool EvaluateIsValid() { string controlValue = GetControlValidationValue(ControlToValidate); if (controlValue == null) { // Provide Validation for CheckBox. if (_isCheckBox) { return(((WebControls.CheckBox)NamingContainer.FindControl(ControlToValidate)).Checked); } // Provide Validation for CheckBoxList. else if (_isCheckBoxList) { WebControls.CheckBoxList c = (WebControls.CheckBoxList)NamingContainer.FindControl(ControlToValidate); foreach (WebControls.ListItem item in c.Items) { if (item.Selected) { return(true); } } return(false); } // Get the control value, return true if it is not found Debug.Fail("Should have been caught by PropertiesValid check"); return(true); } // See if the control has changed return(!controlValue.Trim().Equals(InitialValue.Trim())); }
public IEnumerable <ValidationFailure> ApplyValidationFailures(IEnumerable <ValidationFailure> failures) { var control = NamingContainer.FindControl(ControlToValidate); var bocControl = control as BusinessObjectReferenceDataSourceControl; if (bocControl == null) { throw new InvalidOperationException("BocReferenceDataSourceValidator may only be applied to controls of type BusinessObjectReferenceDataSourceControl"); } _validationFailures = new List <ValidationFailure> (); foreach (var failure in failures) { if (IsMatchingControl(failure, bocControl)) { _validationFailures.Add(failure); } else { yield return(failure); } } if (_validationFailures.Any()) { Validate(); } ErrorMessage = string.Join("\r\n", _validationFailures.Select(f => f.ErrorMessage)); }
protected override void AddAttributesToRender(HtmlTextWriter writer) { base.AddAttributesToRender(writer); if (!String.IsNullOrEmpty(AssociatedControlID)) { writer.AddAttribute(HtmlTextWriterAttribute.For, NamingContainer.FindControl(AssociatedControlID).ClientID); } }
private String GetOnClick() { return(string.Format("toggleCollapse(this,'{0}','{1}','{2}','{3}','{4}','{5}');", this.imgToggle.ClientID, NamingContainer.FindControl(ControlToCollapse).ClientID, this.ResolveUrl(this.CollapseImageUrl), this.ResolveUrl(this.ExpandImageUrl), this.CollapseText, this.ExpandText)); }
protected void DependentFromControlChangedHandler(object sender, EventArgs e) { // find data control if (DataContextControl != null && (NamingContainer.FindControl(DataContextControl) as DataContextHolder) != null) { DataContext = ((DataContextHolder)NamingContainer.FindControl(DataContextControl)).GetDataContext(); radiobuttonlist.DataBind(); } //DataBind(); }
protected string GetControlRenderID(string name) { Control control = NamingContainer.FindControl(name); if (control == null) { return(null); } return(control.ClientID); }
private DataSourceView ConnectToDataSourceView() { // If the current view is correct, there is no need to reconnect if (_currentViewValid && !DesignMode) return _currentView; // Disconnect from old view, if necessary if ((_currentView != null) && (_currentViewIsFromDataSourceID)) { // We only care about this event if we are bound through the DataSourceID property _currentView.DataSourceViewChanged -= new EventHandler(OnDataSourceViewChanged); } // Connect to new view IDataSource ds = null; string dataSourceID = DataSourceID; if (!string.IsNullOrEmpty(dataSourceID)) { // Try to find a DataSource control with the ID specified in DataSourceID Control control = NamingContainer.FindControl(dataSourceID); if (control == null) throw new HttpException(String.Format(CultureInfo.CurrentCulture, "DataSource '{1}' for control '{0}' doesn't exist", ID, dataSourceID)); ds = control as IDataSource; if (ds == null) throw new HttpException(String.Format(CultureInfo.CurrentCulture, "'{1}' is not a data source for control '{0}'.", ID, dataSourceID)); } if (ds == null) { // DataSource control was not found, construct a temporary data source to wrap the data return null; } else { // Ensure that both DataSourceID as well as DataSource are not set at the same time if (DataSource != null) throw new InvalidOperationException("DataSourceID and DataSource can't be set at the same time."); } // IDataSource was found, extract the appropriate view and return it DataSourceView newView = ds.GetView(DataMember); if (newView == null) throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "DataSourceView not found for control '{0}'", ID)); _currentViewIsFromDataSourceID = IsBoundUsingDataSourceID; _currentView = newView; // If we're bound through the DataSourceID proeprty, then we care about this event if ((_currentView != null) && (_currentViewIsFromDataSourceID)) _currentView.DataSourceViewChanged += new EventHandler(OnDataSourceViewChanged); _currentViewValid = true; return _currentView; }
protected void DependentFromControlChangedHandler(object sender, EventArgs e) { // find data control if (DataContextControl != null && (NamingContainer.FindControl(DataContextControl) as DataContextHolder) != null) { LookupDataContext = ((DataContextHolder)NamingContainer.FindControl(DataContextControl)).GetDataContext(); foreach (Control childCtrl in Controls) { childCtrl.DataBind(); } } }
public IEnumerable <ValidationFailure> ApplyValidationFailures(IEnumerable <ValidationFailure> failures) { var control = NamingContainer.FindControl(ControlToValidate); var dataSourceControl = control as BindableObjectDataSourceControl; if (dataSourceControl == null) { throw new InvalidOperationException("BocDataSourceValidator may only be applied to controls of type BindableObjectDataSourceControl."); } // Can only find Validation errors for controls located within the same NamingContainer as the DataSource. // This applies also to ReferenceDataSources. var namingContainer = dataSourceControl.NamingContainer; var validators = EnumerableUtility.SelectRecursiveDepthFirst( namingContainer, child => child.Controls.Cast <Control>().Where(item => !(item is INamingContainer))) .OfType <IBocValidator>(); var unhandledFailures = failures; var referenceDataSourceValidators = new List <BocReferenceDataSourceValidator>(); // ReSharper disable LoopCanBeConvertedToQuery foreach (var validator in validators) // ReSharper restore LoopCanBeConvertedToQuery { if (validator is BocReferenceDataSourceValidator) { referenceDataSourceValidators.Add((BocReferenceDataSourceValidator)validator); } else { unhandledFailures = validator.ApplyValidationFailures(unhandledFailures); } } // ReSharper disable LoopCanBeConvertedToQuery foreach (var validator in referenceDataSourceValidators) // ReSharper restore LoopCanBeConvertedToQuery { unhandledFailures = validator.ApplyValidationFailures(unhandledFailures); } _unhandledFailures = unhandledFailures.ToList(); ErrorMessage = string.Join("\r\n", _unhandledFailures.Select(f => f.ErrorMessage)); if (_unhandledFailures.Any()) { Validate(); } return(_unhandledFailures); }
protected override void OnLoad(EventArgs e) { if (DependentFromControls != null) { foreach (var depCtrlId in DependentFromControls) { if ((NamingContainer.FindControl(depCtrlId) as IEditableTextControl) != null) { ((IEditableTextControl)NamingContainer.FindControl(depCtrlId)).TextChanged += new EventHandler(DependentFromControlChangedHandler); } } } }
[Test] // bug #82546 public void FindControl_NamingContainer () { Control topControl = new NamingContainer (); topControl.ID = "top"; Control controlLevel1A = new Control (); controlLevel1A.ID = "Level1#A"; topControl.Controls.Add (controlLevel1A); Control controlLevel1B = new Control (); controlLevel1B.ID = "Level1#B"; topControl.Controls.Add (controlLevel1B); Control controlLevel2AA = new Control (); controlLevel2AA.ID = "Level2#AA"; controlLevel1A.Controls.Add (controlLevel2AA); Control controlLevel2AB = new Control (); controlLevel2AB.ID = "Level2#AB"; controlLevel1A.Controls.Add (controlLevel2AB); Control foundControl = topControl.FindControl ("Level1#A"); Assert.IsNotNull (foundControl, "#A1"); Assert.AreSame (controlLevel1A, foundControl, "#A2"); foundControl = topControl.FindControl ("LEVEL1#B"); Assert.IsNotNull (foundControl, "#B1"); Assert.AreSame (controlLevel1B, foundControl, "#B2"); foundControl = topControl.FindControl ("LeVeL2#AB"); Assert.IsNotNull (foundControl, "#C1"); Assert.AreSame (controlLevel2AB, foundControl, "#C2"); foundControl = topControl.FindControl ("doesnotexist"); Assert.IsNull (foundControl, "#D1"); foundControl = topControl.FindControl ("top"); Assert.IsNull (foundControl, "#D2"); foundControl = controlLevel1A.FindControl ("Level2#AA"); Assert.IsNotNull (foundControl, "#E1"); Assert.AreSame (controlLevel2AA, foundControl, "#E2"); foundControl = controlLevel1A.FindControl ("LEveL2#ab"); Assert.IsNotNull (foundControl, "#F1"); Assert.AreSame (controlLevel2AB, foundControl, "#F2"); }