private static bool ValidatePathIsReadable(GalleryServerPro.WebControls.wwDataBindingItem item, string pathToTest, Label pathLabel) { // Verify that the IIS process identity has read permission to the specified path. bool isValid = false; string fullPhysicalPath = HelperFunctions.CalculateFullPath(AppSetting.Instance.PhysicalApplicationPath, pathToTest); try { HelperFunctions.ValidatePhysicalPathExistsAndIsReadable(fullPhysicalPath); isValid = true; } catch (GalleryServerPro.Events.CustomExceptions.CannotReadFromDirectoryException ex) { item.BindingErrorMessage = ex.Message; } if (isValid) { pathLabel.Text = fullPhysicalPath; pathLabel.CssClass = "gsp_msgfriendly"; } else { pathLabel.Text = String.Concat("<", Resources.GalleryServerPro.Admin_MediaObjects_InvalidPath, ">"); pathLabel.CssClass = "gsp_msgwarning"; } return(isValid); }
/// <summary> /// Handles the OnValidateControl event of the wwDataBinder control. /// </summary> /// <param name="item">The wwDataBindingItem item.</param> /// <returns>Returns <c>true</c> if the item is valid; otherwise returns <c>false</c>.</returns> protected bool wwDataBinder_ValidateControl(GalleryServerPro.WebControls.wwDataBindingItem item) { // Validate various settings to make sure they don't conflict with each other. if (item.ControlInstance == this.txtMoPath) { return(ValidateMediaObjectPath(item)); } else if (item.ControlInstance == this.txtThumbnailCachePath) { return(ValidateThumbnailPath(item)); } else if (item.ControlInstance == this.txtOptimizedCachePath) { return(ValidateOptimizedPath(item)); } else if (item.ControlInstance == this.chkPathIsReadOnly) { return(ValidateMediaObjectPath(item)); // Validate the "media files are read-only" option } return(true); }
/// <summary> /// Adds a binding error to the collection of binding errors. /// </summary> /// <param name="ErrorMessage"></param> /// <param name="control"></param> /// <returns>false if the control was not able to get a control reference to attach hotlinks and an icon. Error message always gets added</returns> public bool AddBindingError(string ErrorMessage, Control Control) { wwDataBindingItem DataBindingItem = null; if (Control == null) { this.BindingErrors.Add(new BindingError(ErrorMessage)); return(false); } foreach (wwDataBindingItem Ctl in this.DataBindingItems) { if (Ctl.ControlId == Control.ID) { Ctl.ControlInstance = Control; DataBindingItem = Ctl; break; } } // *** No associated control found - just add the error message if (DataBindingItem == null) { this.BindingErrors.Add(new BindingError(ErrorMessage, Control.ClientID)); return(false); } return(this.AddBindingError(ErrorMessage, DataBindingItem)); }
protected bool wwDataBinder_ValidateControl(GalleryServerPro.WebControls.wwDataBindingItem item) { if (item.ControlInstance == txtMaxErrorItems) { if ((chkAutoTrimLog.Checked) && (Convert.ToInt32(txtMaxErrorItems.Text) <= 0)) { item.BindingErrorMessage = Resources.GalleryServerPro.Admin_Error_Invalid_MaxNumberErrorItems_Msg; return(false); } } if (item.ControlInstance == txtJQueryScriptPath) { if (!ValidateUrl(txtJQueryScriptPath.Text.Trim())) { item.BindingErrorMessage = Resources.GalleryServerPro.Admin_Site_Settings_InvalidJQueryPath; return(false); } } if (item.ControlInstance == txtJQueryUiScriptPath) { if (!ValidateUrl(txtJQueryUiScriptPath.Text.Trim())) { item.BindingErrorMessage = Resources.GalleryServerPro.Admin_Site_Settings_InvalidJQueryPath; return(false); } } return(true); }
private bool ValidatePathIsWritable(GalleryServerPro.WebControls.wwDataBindingItem item, string fullPathToTest) { // Verify that the IIS process identity has write permission to the specified path. // We only need to execute this once for each unique path. If we already tested this path, then return that test result. This helps // prevent the same error message from being shown multiple times. if (_pathsThatHaveBeenTestedForWriteability.ContainsKey(fullPathToTest)) { return(_pathsThatHaveBeenTestedForWriteability[fullPathToTest]); } bool isValid = false; try { HelperFunctions.ValidatePhysicalPathExistsAndIsReadWritable(fullPathToTest); isValid = true; } catch (GalleryServerPro.Events.CustomExceptions.CannotWriteToDirectoryException ex) { item.BindingErrorMessage = ex.Message; } // Set the flag so we don't have to repeat the validation later in the page lifecycle. _pathsThatHaveBeenTestedForWriteability.Add(fullPathToTest, isValid); return(isValid); }
// <summary> /// Creates the text for binding error messages based on the /// BindingErrorMessage property of a data bound control. /// /// If set the control calls this method render the error message. Called by /// the various controls to generate the error HTML based on the <see>Enum /// ErrorMessageLocations</see>. /// /// If UseClientScriptHtmlInjection is set the error message is injected /// purely through a client script JavaScript function which avoids problems /// with Controls.Add() when script tags are present in the container. /// <seealso>Class wwWebDataHelper</seealso> /// </summary> /// <param name="control"> /// Instance of the control that has an error. /// </param> /// <returns>String</returns> internal string GetBindingErrorMessageHtml(wwDataBindingItem Item) { string Image = null; if (string.IsNullOrEmpty(this.ErrorIconUrl) || this.ErrorIconUrl == "WebResource") { Image = this.ErrorIconWebResource; } else { Image = this.ResolveUrl(this.ErrorIconUrl); } string Message = ""; if (Item.ErrorMessageLocation == BindingErrorMessageLocations.WarningIconRight) { Message = string.Format(CultureInfo.CurrentCulture, " <img src=\"{0}\" alt=\"{1}\" />", Image, Item.BindingErrorMessage); } else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.RedTextBelow) { Message = "<br /><span style=\"color:red;\"><smaller>" + Item.BindingErrorMessage + "</smaller></span>"; } else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.RedTextAndIconBelow) { Message = string.Format(CultureInfo.CurrentCulture, "<br /><img src=\"{0}\"> <span style=\"color:red;\" /><smaller>{1}</smaller></span>", Image, Item.BindingErrorMessage); } else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.None) { Message = ""; } else { Message = "<span style='color:red;font-weight:bold;'> * </span>"; } // *** Fix up message so ' are allowed Message = Message.Replace("'", @"\'"); // *** Use Client Side JavaScript to inject the message rather than adding a control if (this.UseClientScriptHtmlInjection && Item.ControlInstance != null) { if (!this._ClientScriptInjectionScriptAdded) { this.AddScriptForAddHtmlAfterControl(); } this.Page.ClientScript.RegisterStartupScript(this.GetType(), Item.ControlId, string.Format(CultureInfo.CurrentCulture, "AddHtmlAfterControl('{0}','{1}');\r\n", Item.ControlInstance.ClientID, Message), true); // *** Message is handled in script so nothing else to write Message = ""; } // *** Message will be embedded with a Literal Control return(Message); }
protected void wwDataBinder_AfterBindControl(GalleryServerPro.WebControls.wwDataBindingItem item) { // We need to HTML decode the role name that appears in the combo box if (item.ControlId == cboUserRoles.ID) { cboUserRoles.Text = Util.HtmlDecode(cboUserRoles.Text); } }
/// <summary> /// Fires the ValidateControlEvent /// </summary> /// <param name="Item"></param> /// <returns>false - Validation for control failed and a BindingError is added, true - Validation succeeded</returns> public bool OnValidateControl(wwDataBindingItem Item) { if (this.ValidateControl != null && !this.ValidateControl(Item)) { return(false); } return(true); }
/// <summary> /// Manages errors that occur during unbinding. Sets BindingErrors collection and /// and writes out validation error display to the page if specified /// </summary> /// <param name="Item"></param> /// <param name="ex"></param> private void HandleUnbindingError(wwDataBindingItem Item, Exception ex) { Item.IsBindingError = true; // *** Display Error info by setting BindingErrorMessage property try { string ErrorMessage = null; // *** Must check that the control exists - if invalid ID was // *** passed there may not be an instance! if (Item.ControlInstance == null) { ErrorMessage = "Invalid Control: " + Item.ControlId; } else { string DerivedUserFieldName = this.DeriveUserFieldName(Item); if (ex is RequiredFieldException) { ErrorMessage = DerivedUserFieldName + " can't be left empty"; } else if (ex is ValidationErrorException) { /// *** Binding Error Message will be set ErrorMessage = ex.Message; } // *** Explicit error message returned else if (ex is BindingErrorException) { ErrorMessage = ex.Message + " for " + DerivedUserFieldName; } else { if (string.IsNullOrEmpty(Item.BindingErrorMessage)) { ErrorMessage = DerivedUserFieldName + ": " + ex.Message; // Change to this 2009.01.26 to yield a more informative message } //ErrorMessage = "Invalid format for " + DerivedUserFieldName; else { // *** Control has a pre-assigned error message ErrorMessage = Item.BindingErrorMessage; } } } this.AddBindingError(ErrorMessage, Item); } catch (Exception) { this.AddBindingError("Binding Error", Item); } }
/// <summary> /// This method only adds a data binding item, but doesn't bind it /// to anything. This can be useful for only displaying errors /// </summary> /// <param name="ControlToBind"></param> /// <returns></returns> public wwDataBindingItem AddBinding(Control ControlToBind) { wwDataBindingItem Item = new wwDataBindingItem(this); Item.ControlInstance = ControlToBind; Item.ControlId = ControlToBind.ID; Item.Page = this.Page; this.DataBindingItems.Add(Item); return(Item); }
/// <summary> /// Adds a binding to the control. This method is a simple /// way to establish a binding. /// /// Returns the Item so you can customize properties further /// </summary> /// <param name="ControlToBind"></param> /// <param name="ControlPropertyToBind"></param> /// <param name="SourceObjectToBindTo"></param> /// <param name="SourceMemberToBindTo"></param> public wwDataBindingItem AddBinding(Control ControlToBind, string ControlPropertyToBind, object SourceObjectToBindTo, string SourceMemberToBindTo) { wwDataBindingItem Item = new wwDataBindingItem(this); Item.ControlInstance = ControlToBind; Item.ControlId = ControlToBind.ID; Item.BindingSourceObject = SourceObjectToBindTo; Item.BindingSourceMember = SourceMemberToBindTo; this.DataBindingItems.Add(Item); return(Item); }
private bool ValidateReadOnlyGallery(GalleryServerPro.WebControls.wwDataBindingItem item) { // When a gallery is read only, the following must be true: // 1. The thumbnail and optimized path must be different than the media object path. // 2. The SynchAlbumTitleAndDirectoryName setting must be false. // 3. User albums must be disabled. // We only need to execute this once on a postback. If we already ran it, then return our previous result. This helps // prevent the same error message from being shown multiple times. if (_validateReadOnlyGalleryHasExecuted) { return(_validateReadOnlyGalleryResult); } bool isValid = true; string mediaObjectPath = this.txtMoPath.Text; string thumbnailPath = (String.IsNullOrEmpty(this.txtThumbnailCachePath.Text) ? mediaObjectPath : this.txtThumbnailCachePath.Text); string optimizedPath = (String.IsNullOrEmpty(this.txtOptimizedCachePath.Text) ? mediaObjectPath : this.txtOptimizedCachePath.Text); // 1. The thumbnail and optimized path must be different than the media object path. if ((mediaObjectPath.Equals(thumbnailPath, StringComparison.OrdinalIgnoreCase)) || (mediaObjectPath.Equals(optimizedPath, StringComparison.OrdinalIgnoreCase))) { isValid = false; item.BindingErrorMessage = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Admin_MediaObjects_Cannot_Set_MO_Path_Read_Only_Cache_Location_Not_Set, mediaObjectPath, thumbnailPath, optimizedPath); } // 2. The SynchAlbumTitleAndDirectoryName setting must be false. if (chkSynchAlbumTitleAndDirectoryName.Checked) { isValid = false; item.BindingErrorMessage = Resources.GalleryServerPro.Admin_MediaObjects_Cannot_Set_MO_Path_Read_Only_Synch_Title_And_Directory_Enabled; } // 3. User albums must be disabled. if (GallerySettings.EnableUserAlbum) { isValid = false; item.BindingErrorMessage = Resources.GalleryServerPro.Admin_MediaObjects_Cannot_Set_MO_Path_Read_Only_User_Albums_Enabled; } // Set the flag so we don't have to repeat the validation later in the page lifecycle. this._validateReadOnlyGalleryHasExecuted = true; this._validateReadOnlyGalleryResult = isValid; return(isValid); }
/// <summary> /// Add a wwDataBindingItem to the collection /// </summary> /// <param name="index"></param> /// <param name="Item"></param> public void AddAt(int index, wwDataBindingItem Item) { if (_ParentDataBinder != null) { Item.Page = _ParentDataBinder.Page; Item.Binder = _ParentDataBinder; // *** VS Designer adds new items as soon as their accessed // *** but items may not be valid so we have to clean up if (this._ParentDataBinder.DesignMode) { UpdateListInDesignMode(); } } InnerList.Insert(index, Item); }
/// <summary> /// Add a wwDataBindingItem to the collection /// </summary> /// <param name="Item"></param> public void Add(wwDataBindingItem Item) { if (_ParentDataBinder != null) { Item.Page = _ParentDataBinder.Page; Item.Binder = _ParentDataBinder; // *** VS Designer adds new items as soon as their accessed // *** but items may not be valid so we have to clean up if (this._ParentDataBinder.DesignMode) { // *** Remove any blank items UpdateListInDesignMode(); } } this.InnerList.Add(Item); }
/// <summary> /// Adds a binding error for DataBindingItem control. This is the most efficient /// way to add a BindingError. The other overloads call into this method after /// looking up the Control in the DataBinder. /// </summary> /// <param name="ErrorMessage"></param> /// <param name="BindingItem"></param> /// <returns></returns> public bool AddBindingError(string ErrorMessage, wwDataBindingItem BindingItem) { // *** Associated control found - add icon and link id if (BindingItem.ControlInstance != null) { this.BindingErrors.Add(new BindingError(ErrorMessage, BindingItem.ControlInstance.ClientID)); } else { // *** Just set the error message this.BindingErrors.Add(new BindingError(ErrorMessage)); return(false); } BindingItem.BindingErrorMessage = ErrorMessage; // *** Insert the error text/icon as a literal if (this.ShowBindingErrorsOnControls && BindingItem.ControlInstance != null) { // *** Retrieve the Html Markup for the error // *** NOTE: If script code injection is enabled this is done with client // *** script code to avoid Controls.Add() functionality which may not // *** always work reliably if <%= %> tags are in document. Script HTML injection // *** is the preferred behavior as it should work on any page. If script is used // *** the message returned is blank and the startup script is embedded instead string HtmlMarkup = this.GetBindingErrorMessageHtml(BindingItem); if (!string.IsNullOrEmpty(HtmlMarkup)) { LiteralControl Literal = new LiteralControl(HtmlMarkup); Control Parent = BindingItem.ControlInstance.Parent; int CtlIdx = Parent.Controls.IndexOf(BindingItem.ControlInstance); try { // *** Can't add controls to the Control collection if <%= %> tags are on the page Parent.Controls.AddAt(CtlIdx + 1, Literal); } catch {; } } } return(true); }
/// <summary> /// Returns a UserField name. Returns UserFieldname if set, or if not /// attempts to derive the name based on the field. /// </summary> /// <param name="Control"></param> /// <returns></returns> protected string DeriveUserFieldName(wwDataBindingItem Item) { if (!string.IsNullOrEmpty(Item.UserFieldName)) { return(Item.UserFieldName); } string ControlID = Item.ControlInstance.ID; // *** Try to get a name by stripping of control prefixes string ControlName = Regex.Replace(Item.ControlInstance.ID, "^txt|^chk|^lst|^rad|", "", RegexOptions.IgnoreCase); if (ControlName != ControlID) { return(ControlName); } // *** Nope - use the default ID return(ControlID); }
/// <summary> /// Verifies the currently logged-on user has permission to specify the <paramref name="mediaObjectPath"/> in this gallery. The /// path must not be used by any other galleries unless the user is a gallery admin for each of those galleries or a site /// admin. Returns <c>true</c> if the user has permission; otherwise returns <c>false</c>. /// </summary> /// <param name="item">The binding item representing the control being tested.</param> /// <param name="mediaObjectPath">The relative or full file path the user wishes to use to store media objects, whether they are /// the original media object files, thumbnails, or optimized image files. Relative paths should be relative /// to the root of the running application so that, when it is combined with physicalAppPath parameter, it creates a valid path. /// Examples: "C:\inetpub\wwwroot\galleryserverpro\myimages\", "C:/inetpub/wwwroot/galleryserverpro/myimages", /// "\myimages\", "\myimages", "myimages\", "myimages", "/myimages/", "/myimages"</param> /// <returns> /// Returns <c>true</c> if the user has permission; otherwise returns <c>false</c>. /// </returns> private bool ValidateUserHasPermissionToSpecifyPath(GalleryServerPro.WebControls.wwDataBindingItem item, string mediaObjectPath) { if (UserCanAdministerSite) { return(true); // Site admins always have permission. } if (!UserCanAdministerGallery) { return(false); // Must be at least a gallery admin. Kind of a redundant test but we include it for extra safety. } string fullMediaObjectPath = HelperFunctions.CalculateFullPath(AppSetting.Instance.PhysicalApplicationPath, mediaObjectPath); bool isValid = true; // Get a list of galleries the current user is a gallery admin for. IGalleryCollection adminGalleries = UserController.GetGalleriesCurrentUserCanAdminister(); // Iterate through each gallery and check to see if the path is used in it. foreach (IGallery gallery in Factory.LoadGalleries()) { if (gallery.GalleryId == GalleryId) { continue; // No need to evaluate the current gallery } IGallerySettings gallerySettings = Factory.LoadGallerySetting(gallery.GalleryId); if ((fullMediaObjectPath.Equals(gallerySettings.FullMediaObjectPath, StringComparison.OrdinalIgnoreCase)) || (fullMediaObjectPath.Equals(gallerySettings.FullThumbnailPath, StringComparison.OrdinalIgnoreCase)) || (fullMediaObjectPath.Equals(gallerySettings.FullOptimizedPath, StringComparison.OrdinalIgnoreCase))) { // We found another gallery that is using this path. This is not valid unless the user is a gallery admin for it. if (!adminGalleries.Contains(gallery)) { isValid = false; item.BindingErrorMessage = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Admin_MediaObjects_MO_Path_Used_By_Another_Gallery, mediaObjectPath); } } } return(isValid); }
/// <summary> /// Adds a binding error message to a specific control attached to this binder /// BindingErrors collection. /// </summary> /// <param name="ControlName">Form relative Name (ID) of the control to set the error on</param> /// <param name="ErrorMessage">The Error Message to set it to.</param> /// <returns>true if the control was found. False if not found, but message is still assigned</returns> public bool AddBindingError(string ErrorMessage, string ControlName) { wwDataBindingItem DataBindingItem = null; foreach (wwDataBindingItem Ctl in this.DataBindingItems) { if (Ctl.ControlId == ControlName) { DataBindingItem = Ctl; break; } } if (DataBindingItem == null) { this.BindingErrors.Add(new BindingError(ErrorMessage)); return(false); } return(this.AddBindingError(ErrorMessage, DataBindingItem)); }
/// <summary> /// Returns a specific DataBinding Item for a given control. /// Always returns an item even if the Control is not found. /// If you need to check whether this is a valid item check /// the BindingSource property for being blank. /// /// Extender Property Get method /// </summary> /// <param name="control"></param> /// <returns></returns> public wwDataBindingItem GetDataBindingItem(Control control) { foreach (wwDataBindingItem Item in this.DataBindingItems) { if (Item.ControlId == control.ID) { // *** Ensure the binder is set on the item Item.Binder = this; return(Item); } } wwDataBindingItem NewItem = new wwDataBindingItem(this); NewItem.ControlId = control.ID; NewItem.ControlInstance = control; this.DataBindingItems.Add(NewItem); return(NewItem); }
protected bool wwDataBinder_BeforeUnbindControl(GalleryServerPro.WebControls.wwDataBindingItem item) { // When auto trim is disabled, we store "0" in the config file. if (item.ControlId == chkAutoTrimLog.ID) { if (!chkAutoTrimLog.Checked) { txtMaxErrorItems.Text = "0"; } } if (item.ControlId == txtJQueryScriptPath.ID) { string url = txtJQueryScriptPath.Text.Trim(); if (!String.IsNullOrEmpty(url) && !Util.IsAbsoluteUrl(url) && (!url.StartsWith("~"))) { url = String.Concat("~", url); // Ensure relative URLs start with "~" } txtJQueryScriptPath.Text = url; } if (item.ControlId == txtJQueryUiScriptPath.ID) { string url = txtJQueryUiScriptPath.Text.Trim(); if (!String.IsNullOrEmpty(url) && !Util.IsAbsoluteUrl(url) && (!url.StartsWith("~"))) { url = String.Concat("~", url); // Ensure relative URLs start with "~" } txtJQueryUiScriptPath.Text = url; } return(true); }
protected void wwDataBinder_AfterBindControl(GalleryServerPro.WebControls.wwDataBindingItem item) { // if (item.ControlInstance == txtMaxErrorItems) { int maxErrorItems = Convert.ToInt32(this.txtMaxErrorItems.Text); if (maxErrorItems == 0) { // Disable the checkbox because feature is turned off (a "0" indicates it is off). Set textbox to // an empty string because we don't want to display 0. chkAutoTrimLog.Checked = false; txtMaxErrorItems.Text = String.Empty; } else if (maxErrorItems > 0) { chkAutoTrimLog.Checked = true; // Select the checkbox when max # of items is > 0 } else { // We'll never get here because the config definition uses an IntegerValidator to force the number // to be greater than 0. } } }
/// <summary> /// Verifies the <paramref name="fullPathToTest" /> is valid and the logged-on user has the necessary permission to specify it. /// </summary> /// <param name="item">The binding item representing the control being tested.</param> /// <param name="fullPathToTest">The full file path the user wishes to use to store media objects, whether they are /// the original media object files, thumbnails, or optimized image files. /// Examples: "C:\inetpub\wwwroot\galleryserverpro\myimages\", "C:/inetpub/wwwroot/galleryserverpro/myimages"</param> /// <param name="pathDisplayControl">The Label control used to display the full, calculated path.</param> /// <param name="displayType">Indicates whether the <paramref name="fullPathToTest" /> is the path for the original, thumbnail, /// or optimized media object files.</param> /// <returns> /// Returns <c>true</c> if the path is valid; otherwise returns <c>false</c>. /// </returns> private bool ValidatePath(wwDataBindingItem item, string fullPathToTest, Label pathDisplayControl, DisplayObjectType displayType) { if (_validatePathFailed) { // To help prevent repeated error messages (one each for original, thumbnail, and optimized), if a previous execution of // this test has failed, then let's just return true, thus allowing the user to focus on a single message. return true; } bool isValid; if (this.chkPathIsReadOnly.Checked) { if (displayType == DisplayObjectType.Original) { isValid = ValidateReadOnlyGallery(item) && ValidatePathIsReadable(item, fullPathToTest, pathDisplayControl); } else { isValid = ValidateReadOnlyGallery(item) && ValidatePathIsWritable(item, fullPathToTest); } } else isValid = ValidatePathIsWritable(item, fullPathToTest); isValid = isValid && ValidateUserHasPermissionToSpecifyPath(item, fullPathToTest); if (isValid) { pathDisplayControl.Text = fullPathToTest; pathDisplayControl.CssClass = "gsp_msgfriendly"; } else { if (!this.GallerySettings.FullMediaObjectPath.Equals(fullPathToTest, StringComparison.OrdinalIgnoreCase)) { pathDisplayControl.Text = String.Concat("<", Resources.GalleryServerPro.Admin_MediaObjects_InvalidPath, ">"); pathDisplayControl.CssClass = "gsp_msgwarning"; } _validatePathFailed = true; } return isValid; }
private bool BeforeUnbind_ProcessDisplayBehaviorControls(wwDataBindingItem item) { // When allow HTML is unchecked, several child items are disabled via javascript. Disabled HTML items are not // posted during a postback, so we don't have accurate information about their states. For these controls don't save // anything by returning false. Furthermore, to prevent these child controls from incorrectly reverting to an // empty or unchecked state in the UI, assign their properties to their config setting. if (!this.chkShowHeader.Checked) { if (item.ControlId == this.txtWebsiteTitle.ID) { txtWebsiteTitle.Text = GallerySettingsUpdateable.GalleryTitle; return false; } if (item.ControlId == this.txtWebsiteTitleUrl.ID) { txtWebsiteTitleUrl.Text = GallerySettingsUpdateable.GalleryTitleUrl; return false; } if (item.ControlId == this.chkShowLogin.ID) { this.chkShowLogin.Checked = GallerySettingsUpdateable.ShowLogin; return false; } if (item.ControlId == this.chkShowSearch.ID) { this.chkShowSearch.Checked = GallerySettingsUpdateable.ShowSearch; return false; } } if (!this.chkSendEmail.Checked) { if (item.ControlId == this.cboUsersToNotify.ID) { cboUsersToNotify.Text = String.Empty; return false; } } return true; }
private bool ValidateThumbnailPath(wwDataBindingItem item) { string pathToTest = (String.IsNullOrEmpty(this.txtThumbnailCachePath.Text.Trim()) ? this.txtMoPath.Text.Trim() : this.txtThumbnailCachePath.Text.Trim()); string fullPathToTest = HelperFunctions.CalculateFullPath(AppSetting.Instance.PhysicalApplicationPath, pathToTest); return ValidatePath(item, fullPathToTest, this.lblThumbnailCachePath, DisplayObjectType.Thumbnail); }
private bool BeforeUnbind_ProcessUserAccountControls(wwDataBindingItem item) { // When allow HTML is unchecked, several child items are disabled via javascript. Disabled HTML items are not // posted during a postback, so we don't have accurate information about their states. For these controls don't save // anything by returning false. Furthermore, to prevent these child controls from incorrectly reverting to an // empty or unchecked state in the UI, assign their properties to their config setting. // Step 1: Handle the "allow HTML" checkbox if (!chkAllowHtml.Checked) { if (item.ControlId == txtAllowedHtmlTags.ID) { txtAllowedHtmlTags.Text = AllowedHtmlTags; return false; } if (item.ControlId == txtAllowedHtmlAttributes.ID) { txtAllowedHtmlAttributes.Text = AllowedHtmlAttributes; return false; } } else { // User may have hit Return while editing one of the textboxes. Remove any return characters to be safe. if (item.ControlId == txtAllowedHtmlTags.ID) { txtAllowedHtmlTags.Text = txtAllowedHtmlTags.Text.Replace("\r\n", String.Empty); } if (item.ControlId == txtAllowedHtmlAttributes.ID) { txtAllowedHtmlAttributes.Text = txtAllowedHtmlAttributes.Text.Replace("\r\n", String.Empty); } } // Step 2: Handle the "allow user account management" checkbox if (!this.chkAllowManageAccount.Checked) { if (item.ControlId == this.chkAllowDeleteOwnAccount.ID) { this.chkAllowDeleteOwnAccount.Checked = GallerySettingsUpdateable.AllowDeleteOwnAccount; return false; } } return true; }
private bool ValidateUserCanEnableSelfRegistration(wwDataBindingItem item) { if ((item.ControlInstance == this.chkEnableSelfRegistration)) { if (!UserCanEditUsersAndRoles) { item.BindingErrorMessage = Resources.GalleryServerPro.Admin_User_Settings_Cannot_Enable_Self_Registration_Msg; return false; } } return true; }
private bool ValidateUserAlbums(wwDataBindingItem item) { if ((item.ControlInstance == this.cboUserAlbumParent) && (chkEnableUserAlbums.Checked)) { // User albums are selected. Make sure an album has been chosen to serve as the container for the user albums. int albumId; if ((tvUC.SelectedNode != null) && (Int32.TryParse(tvUC.SelectedNode.Value, out albumId))) { return true; } else { item.BindingErrorMessage = Resources.GalleryServerPro.Admin_User_Settings_Invalid_UserAlbumParent_Msg; return false; } } return true; }
private bool BeforeUnbind_ProcessEnableSelfRegistrationControls(wwDataBindingItem item) { if (!this.chkEnableSelfRegistration.Checked) { // When self registration is unchecked, several child items are disabled via javascript. Disabled HTML items are not // posted during a postback, so we don't have accurate information about their states. For these controls don't save // anything by returning false. Furthermore, to prevent these child controls from incorrectly reverting to an // empty or unchecked state in the UI, assign their properties to their config setting. if (item.ControlId == this.chkRequireEmailValidation.ID) { this.chkRequireEmailValidation.Checked = GallerySettings.RequireEmailValidationForSelfRegisteredUser; return false; } if (item.ControlId == this.chkRequireAdminApproval.ID) { this.chkRequireAdminApproval.Checked = GallerySettings.RequireApprovalForSelfRegisteredUser; return false; } if (item.ControlId == this.chkUseEmailForAccountName.ID) { this.chkUseEmailForAccountName.Checked = GallerySettings.UseEmailForAccountName; return false; } } return true; }
/// <summary> /// Fires the ValidateControlEvent /// </summary> /// <param name="Item"></param> /// <returns>false - Validation for control failed and a BindingError is added, true - Validation succeeded</returns> public bool OnValidateControl(wwDataBindingItem Item) { if (this.ValidateControl != null && !this.ValidateControl(Item)) return false; return true; }
/// <summary> /// Returns a specific DataBinding Item for a given control. /// Always returns an item even if the Control is not found. /// If you need to check whether this is a valid item check /// the BindingSource property for being blank. /// /// Extender Property Get method /// </summary> /// <param name="control"></param> /// <returns></returns> public wwDataBindingItem GetDataBindingItem(Control control) { foreach (wwDataBindingItem Item in this.DataBindingItems) { if (Item.ControlId == control.ID) { // *** Ensure the binder is set on the item Item.Binder = this; return Item; } } wwDataBindingItem NewItem = new wwDataBindingItem(this); NewItem.ControlId = control.ID; NewItem.ControlInstance = control; this.DataBindingItems.Add(NewItem); return NewItem; }
private bool ValidateMediaObjectPath(wwDataBindingItem item) { string fullPathToTest = HelperFunctions.CalculateFullPath(AppSetting.Instance.PhysicalApplicationPath, this.txtMoPath.Text.Trim()); return ValidatePath(item, fullPathToTest, this.lblMoPath, DisplayObjectType.Original); }
/// <summary> /// Creates the text for binding error messages based on the /// BindingErrorMessage property of a data bound control. /// /// If set the control calls this method render the error message. Called by /// the various controls to generate the error HTML based on the <see>Enum /// ErrorMessageLocations</see>. /// /// If UseClientScriptHtmlInjection is set the error message is injected /// purely through a client script JavaScript function which avoids problems /// with Controls.Add() when script tags are present in the container. /// </summary> /// <param name="Item"> /// Instance of the control that has an error. /// </param> /// <returns>String</returns> internal string GetBindingErrorMessageHtml(wwDataBindingItem Item) { string Image = null; if (string.IsNullOrEmpty(this.ErrorIconUrl) || this.ErrorIconUrl == "WebResource") Image = Web.Utils.GetSkinnedUrl("images/error-s.png"); else Image = this.ResolveUrl(this.ErrorIconUrl); string Message = ""; if (Item.ErrorMessageLocation == BindingErrorMessageLocations.WarningIconRight) Message = String.Format(CultureInfo.CurrentCulture, " <img src=\"{0}\" alt=\"{1}\" />", Image, Item.BindingErrorMessage); else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.RedTextBelow) Message = "<br /><span style=\"color:red;\"><smaller>" + Item.BindingErrorMessage + "</smaller></span>"; else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.RedTextAndIconBelow) Message = String.Format(CultureInfo.CurrentCulture, "<br /><img src=\"{0}\"> <span style=\"color:red;\" /><smaller>{1}</smaller></span>", Image, Item.BindingErrorMessage); else if (Item.ErrorMessageLocation == BindingErrorMessageLocations.None) Message = ""; else Message = "<span style='color:red;font-weight:bold;'> * </span>"; // *** Fix up message so ' are allowed Message = Message.Replace("'", @"\'"); // *** Use Client Side JavaScript to inject the message rather than adding a control if (this.UseClientScriptHtmlInjection && Item.ControlInstance != null) { if (!this._ClientScriptInjectionScriptAdded) this.AddScriptForAddHtmlAfterControl(); this.Page.ClientScript.RegisterStartupScript(this.GetType(), Item.ControlId, String.Format(CultureInfo.CurrentCulture, "AddHtmlAfterControl('{0}','{1}');\r\n", Item.ControlInstance.ClientID, Message), true); // *** Message is handled in script so nothing else to write Message = ""; } // *** Message will be embedded with a Literal Control return Message; }
/// <summary> /// Returns a UserField name. Returns UserFieldname if set, or if not /// attempts to derive the name based on the field. /// </summary> /// <param name="Control"></param> /// <returns></returns> protected string DeriveUserFieldName(wwDataBindingItem Item) { if (!string.IsNullOrEmpty(Item.UserFieldName)) return Item.UserFieldName; string ControlID = Item.ControlInstance.ID; // *** Try to get a name by stripping of control prefixes string ControlName = Regex.Replace(Item.ControlInstance.ID, "^txt|^chk|^lst|^rad|", "", RegexOptions.IgnoreCase); if (ControlName != ControlID) return ControlName; // *** Nope - use the default ID return ControlID; }
/// <summary> /// Manages errors that occur during unbinding. Sets BindingErrors collection and /// and writes out validation error display to the page if specified /// </summary> /// <param name="Item"></param> /// <param name="ex"></param> private void HandleUnbindingError(wwDataBindingItem Item, Exception ex) { Item.IsBindingError = true; // *** Display Error info by setting BindingErrorMessage property try { string ErrorMessage = null; // *** Must check that the control exists - if invalid ID was // *** passed there may not be an instance! if (Item.ControlInstance == null) ErrorMessage = "Invalid Control: " + Item.ControlId; else { string DerivedUserFieldName = this.DeriveUserFieldName(Item); if (ex is RequiredFieldException) { ErrorMessage = DerivedUserFieldName + " can't be left empty"; } else if (ex is ValidationErrorException) { /// *** Binding Error Message will be set ErrorMessage = ex.Message; } // *** Explicit error message returned else if (ex is BindingErrorException) { ErrorMessage = ex.Message + " for " + DerivedUserFieldName; } else { if (string.IsNullOrEmpty(Item.BindingErrorMessage)) ErrorMessage = DerivedUserFieldName + ": " + ex.Message; // Change to this 2009.01.26 to yield a more informative message //ErrorMessage = "Invalid format for " + DerivedUserFieldName; else // *** Control has a pre-assigned error message ErrorMessage = Item.BindingErrorMessage; } } this.AddBindingError(ErrorMessage, Item); } catch (Exception) { this.AddBindingError("Binding Error", Item); } }
private bool ValidateDefaultRolesForSelfRegisteredUser(wwDataBindingItem item) { if ((item.ControlInstance == this.cboUserRoles) && (this.cboUserRoles.Text != Core.DefaultRolesForSelfRegisteredUser)) { // User has updated the list of default roles. Make sure they represent valid roles. foreach (string roleName in this.cboUserRoles.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (!RoleController.RoleExists(Util.HtmlDecode(roleName))) { item.BindingErrorMessage = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Admin_User_Settings_Invalid_Role_Name_Msg, roleName); return false; } } } return true; }
/// <summary> /// Adds a binding error for DataBindingItem control. This is the most efficient /// way to add a BindingError. The other overloads call into this method after /// looking up the Control in the DataBinder. /// </summary> /// <param name="ErrorMessage"></param> /// <param name="BindingItem"></param> /// <returns></returns> public bool AddBindingError(string ErrorMessage, wwDataBindingItem BindingItem) { // *** Associated control found - add icon and link id if (BindingItem.ControlInstance != null) this.BindingErrors.Add(new BindingError(ErrorMessage, BindingItem.ControlInstance.ClientID)); else { // *** Just set the error message this.BindingErrors.Add(new BindingError(ErrorMessage)); return false; } BindingItem.BindingErrorMessage = ErrorMessage; // *** Insert the error text/icon as a literal if (this.ShowBindingErrorsOnControls && BindingItem.ControlInstance != null) { // *** Retrieve the Html Markup for the error // *** NOTE: If script code injection is enabled this is done with client // *** script code to avoid Controls.Add() functionality which may not // *** always work reliably if <%= %> tags are in document. Script HTML injection // *** is the preferred behavior as it should work on any page. If script is used // *** the message returned is blank and the startup script is embedded instead string HtmlMarkup = this.GetBindingErrorMessageHtml(BindingItem); if (!string.IsNullOrEmpty(HtmlMarkup)) { LiteralControl Literal = new LiteralControl(HtmlMarkup); Control Parent = BindingItem.ControlInstance.Parent; int CtlIdx = Parent.Controls.IndexOf(BindingItem.ControlInstance); try { // *** Can't add controls to the Control collection if <%= %> tags are on the page Parent.Controls.AddAt(CtlIdx + 1, Literal); } catch { ; } } } return true; }
private bool ValidateUsersToNotifyWhenAccountIsCreated(wwDataBindingItem item) { if ((item.ControlInstance == this.cboUsersToNotify) && (this.cboUsersToNotify.Text != Core.UsersToNotifyWhenAccountIsCreated)) { // User has updated the list of users to notify. Make sure they represent valid user account names. foreach (string userName in this.cboUsersToNotify.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (UserController.GetUser(Util.HtmlDecode(userName), false) == null) { item.BindingErrorMessage = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Admin_User_Settings_Invalid_User_Name_Msg, userName); return false; } } } return true; }
/// <summary> /// Verify the roles in the DefaultRolesForSelfRegisteredUser setting exist. Returns false if one or more do not exist. The error /// message is assigned to the <see cref="wwDataBindingItem.BindingErrorMessage" /> property of <paramref name="item" />. /// </summary> /// <param name="item">The data binding item.</param> /// <returns>Returns true if every role in the DefaultRolesForSelfRegisteredUser setting exists; otherwise false.</returns> private bool VerifyDefaultRolesForSelfRegisteredUserExist(wwDataBindingItem item) { foreach (string roleName in GallerySettingsUpdateable.DefaultRolesForSelfRegisteredUser) { if (!RoleController.RoleExists(Utils.HtmlDecode(roleName.Trim()))) { item.BindingErrorMessage = String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.Admin_User_Settings_Invalid_Role_Name_Msg, roleName); return false; } } return true; }
protected bool wwDataBinder_ValidateControl(GalleryServerPro.WebControls.wwDataBindingItem item) { // Validate various settings to make sure they don't conflict with each other. return(true); }
/// <summary> /// This method only adds a data binding item, but doesn't bind it /// to anything. This can be useful for only displaying errors /// </summary> /// <param name="ControlToBind"></param> /// <returns></returns> public wwDataBindingItem AddBinding(Control ControlToBind) { wwDataBindingItem Item = new wwDataBindingItem(this); Item.ControlInstance = ControlToBind; Item.ControlId = ControlToBind.ID; Item.Page = this.Page; this.DataBindingItems.Add(Item); return Item; }
private bool BeforeUnbind_ProcessEnableUserAlbumsControls(wwDataBindingItem item) { if (!this.chkEnableUserAlbums.Checked) { // When user albums is unchecked, several child items are disabled via javascript. Disabled HTML items are not // posted during a postback, so we don't have accurate information about their states. For these controls don't save // anything by returning false. Furthermore, to prevent these child controls from incorrectly reverting to an // empty or unchecked state in the UI, assign their properties to their config setting. if (item.ControlId == this.chkRedirectAfterLogin.ID) { this.chkRedirectAfterLogin.Checked = GallerySettings.RedirectToUserAlbumAfterLogin; return false; } if (item.ControlId == this.txtAlbumNameTemplate.ID) { this.txtAlbumNameTemplate.Text = GallerySettings.UserAlbumNameTemplate; return false; } if (item.ControlId == this.txtAlbumSummaryTemplate.ID) { this.txtAlbumSummaryTemplate.Text = GallerySettings.UserAlbumSummaryTemplate; return false; } } return true; }
/// <summary> /// Adds a binding to the control. This method is a simple /// way to establish a binding. /// /// Returns the Item so you can customize properties further /// </summary> /// <param name="ControlToBind"></param> /// <param name="ControlPropertyToBind"></param> /// <param name="SourceObjectNameToBindTo"></param> /// <param name="SourceMemberToBindTo"></param> /// <returns></returns> public wwDataBindingItem AddBinding(Control ControlToBind, string ControlPropertyToBind, string SourceObjectNameToBindTo, string SourceMemberToBindTo) { wwDataBindingItem Item = new wwDataBindingItem(this); Item.ControlInstance = ControlToBind; Item.ControlId = ControlToBind.ID; Item.Page = this.Page; Item.BindingSource = SourceObjectNameToBindTo; Item.BindingSourceMember = SourceMemberToBindTo; this.DataBindingItems.Add(Item); return Item; }
private bool ValidateUserAlbums(wwDataBindingItem item) { if ((item.ControlInstance == this.chkEnableUserAlbums) && (chkEnableUserAlbums.Checked)) { // User albums are selected. Make sure this isn't a read-only gallery. if (GallerySettings.MediaObjectPathIsReadOnly) { item.BindingErrorMessage = Resources.GalleryServerPro.Admin_User_Settings_Cannot_Enable_User_Albums_In_Read_Only_Gallery; return false; } // Make sure an album has been chosen to serve as the container for the user albums. if (tvUC.SelectedAlbum == null) { item.BindingErrorMessage = Resources.GalleryServerPro.Admin_User_Settings_Invalid_UserAlbumParent_Msg; return false; } } return true; }
private bool ValidateDefaultRolesForSelfRegisteredUser(wwDataBindingItem item) { if ((item.ControlInstance == this.cboUserRoles)) { string roleNames = String.Join(", ", GallerySettings.DefaultRolesForSelfRegisteredUser); if ((!this.cboUserRoles.Text.Equals(roleNames))) { // User has updated the list of default roles. Validate. if (!VerifyDefaultRolesForSelfRegisteredUserExist(item)) return false; if (!VerifyUserHasPermissionToAddUserToDefaultRolesForSelfRegisteredUser(item)) return false; } } return true; }
/// <summary> /// Verifies the logged on user has permission to add users to the roles defined in the DefaultRolesForSelfRegisteredUser setting. /// </summary> /// <param name="item">The data binding item.</param> /// <returns>Returns true if logged on user has permission to add users to the roles defined in the DefaultRolesForSelfRegisteredUser setting; /// otherwise false.</returns> private bool VerifyUserHasPermissionToAddUserToDefaultRolesForSelfRegisteredUser(wwDataBindingItem item) { IUserAccount sampleNewUser = new UserAccount(Guid.NewGuid().ToString()); try { UserController.ValidateLoggedOnUserHasPermissionToSaveUser(sampleNewUser, GallerySettingsUpdateable.DefaultRolesForSelfRegisteredUser, null); } catch (GallerySecurityException ex) { item.BindingErrorMessage = ex.Message; return false; } return true; }
private bool ValidateUsersToNotifyWhenErrorOccurs(wwDataBindingItem item) { if ((item.ControlInstance == this.cboUsersToNotify)) { string userNamesCurrent = String.Join(", ", GallerySettings.UsersToNotifyWhenErrorOccurs.GetUserNames()); if ((!this.cboUsersToNotify.Text.Equals(userNamesCurrent))) { // User has updated the list of users to notify. Make sure they represent valid user account names. foreach (string userName in this.cboUsersToNotify.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { IUserAccount user = UserController.GetUser(Utils.HtmlDecode(userName.Trim()), false); if (user == null) { item.BindingErrorMessage = String.Format(CultureInfo.InvariantCulture, Resources.GalleryServerPro.Admin_General_Invalid_User_Name_Msg, userName.Trim()); return false; } if (!HelperFunctions.IsValidEmail(user.Email)) { item.BindingErrorMessage = String.Format(CultureInfo.InvariantCulture, Resources.GalleryServerPro.Admin_General_Invalid_User_Email_Msg, userName.Trim()); return false; } } } } return true; }