internal static HtmlHelper Create(ModelStateDictionary modelStateDictionary = null, ValidationHelper validationHelper = null) { modelStateDictionary = modelStateDictionary ?? new ModelStateDictionary(); var httpContext = new Mock<HttpContextBase>(); validationHelper = validationHelper ?? new ValidationHelper(httpContext.Object, modelStateDictionary); return new HtmlHelper(modelStateDictionary, validationHelper); }
public void AsyncValidation_DependantProperties_IfOneInvalidSecondIsInvalidToo() { TestUtils.ExecuteWithDispatcher((dispatcher, testCompleted) => { var vm = new DummyViewModel { Foo = "abc", Bar = "abc" }; Func<bool> validCondition = () => vm.Foo != vm.Bar; var validation = new ValidationHelper(); validation.AddAsyncRule( () => vm.Foo, () => vm.Bar, setResult => { ThreadPool.QueueUserWorkItem(_ => { setResult(RuleResult.Assert(validCondition(), "Foo must be different than bar")); }); }); validation.ValidateAsync(() => vm.Bar).ContinueWith(r => { Assert.False(r.Result.IsValid, "Validation must fail"); Assert.True(r.Result.ErrorList.Count == 2, "There must be 2 errors: one for each dependant property"); testCompleted(); }); }); }
public void CombineRuleResults_ResultContainsErrorsFromAllCombinedResults() { // Arrange var validation = new ValidationHelper(); validation.AddRule(() => { //var r1 = RuleResult.Invalid("Error1"); //var r2 = RuleResult.Valid(); //var r3 = RuleResult.Invalid("Error2"); return RuleResult.Assert(false, "Error1").Combine( RuleResult.Assert(true, "Error0")).Combine( RuleResult.Assert(false, "Error2")); //return r1.Combine(r2).Combine(r3); }); // Act var result = validation.ValidateAll(); // Assert Assert.False(result.IsValid, "The validation must fail"); Assert.Equal(2, result.ErrorList.Count); Assert.True(result.ErrorList.Any(e => e.ErrorText == "Error1")); Assert.True(result.ErrorList.Any(e => e.ErrorText == "Error2")); }
public FormulateTreeController() { Persistence = EntityPersistence.Current.Manager; FolderHelper = new FolderHelper(Persistence, this); FormHelper = new FormHelper(this, FolderHelper); LayoutHelper = new LayoutHelper(this, FolderHelper); ValidationHelper = new ValidationHelper(this, FolderHelper); }
// PUT api/values/5 public ValidationResult_OSC Put([FromBody]OnlineShoppingCart.Model.Models.Product product) { var result = new ValidationResult_OSC(); ValidationHelper validationHelper = new ValidationHelper(ref result, ModelState); if (result.Success) { Product productDAL = new Product(); result = productDAL.EditProduct(product); } return result; }
public IHttpActionResult GetValidations(string dtoObjectName, string jsonObjectName) { ValidationHelper._errorMessageFormatter = new List<IErrorMessageFormatter> { new DefaultErrorMessageFormatter(), new AttributeErrorMessageFormatter(), // new ResourceErrorMessageFormatter{ResourceNamespace = "Namespace", ResourceAssemblyName = "Assembly"}, }; var valHelper = new ValidationHelper(); object jsonObject = valHelper.GetValidations(dtoObjectName, "AATestAPI.Models", "AATestAPI"); return Ok(jsonObject); }
public void AddRequiredRule_RuleIsAddedForSpecifiedPropertyName() { // ARRANGE var vm = new DummyViewModel(); var v = new ValidationHelper(); v.AddRequiredRule(() => vm.Foo, "Foo required."); // ACT var vr = v.Validate(nameof(vm.Foo)); // VERIFY Assert.False(vr.IsValid); Assert.Equal(vr.ErrorList[0].ErrorText, "Foo required."); }
public void AsyncValidation_GeneralSmokeTest() { TestUtils.ExecuteWithDispatcher((dispatcher, completedAction) => { var vm = new DummyViewModel {Foo = null}; var validation = new ValidationHelper(); bool ruleExecuted = false; // OK, this is really strange, but if Action<bool> is not mentioned anywhere in the project, then ReSharter would fail to build and run the test... // So including the following line to fix it. Action<RuleResult> dummy = null; Assert.Null(dummy); // Getting rid of the "unused variable" warning. validation.AddAsyncRule(setResult => ThreadPool.QueueUserWorkItem(_ => { ruleExecuted = true; setResult(RuleResult.Invalid("Foo cannot be empty string.")); })); validation.ResultChanged += (o, e) => { Assert.True(ruleExecuted, "Validation rule must be executed before ValidationCompleted event is fired."); var isUiThread = dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId; Assert.True(isUiThread, "ValidationResultChanged must be executed on UI thread"); }; var ui = TaskScheduler.FromCurrentSynchronizationContext(); validation.ValidateAllAsync().ContinueWith(r => { var isUiThread = dispatcher.Thread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId; Assert.True(isUiThread, "Validation callback must be executed on UI thread"); Assert.False(r.Result.IsValid, "Validation must fail according to the validaton rule"); Assert.False(validation.GetResult().IsValid, "Validation must fail according to the validaton rule"); Assert.True(ruleExecuted, "Rule must be executed before validation completed callback is executed."); completedAction(); }, ui); }); }
public void AddRequiredRule_AddsRuleThatChecksTheObjectNotNullOrEmptyString() { // ARRANGE var validation = new ValidationHelper(); var dummy = new DummyViewModel(); validation.AddRequiredRule(() => dummy.Foo, "Foo cannot be empty"); // ACT var result = validation.ValidateAll(); // VERIFY Assert.False(result.IsValid, "Validation must fail"); // ACT dummy.Foo = "abc"; var resultAfterCorrection = validation.ValidateAll(); // VERIFY Assert.True(resultAfterCorrection.IsValid, "The result must be valid after the correction of the error"); }
private void saveAccount() { if (password.Text != confirmationPassword.Text) { MessageBox.Show("Password Mismatch, please ensure the two passwords provided match."); return; } String accountName = ""; try { accountName = accountTypeListBox.SelectedItem.ToString(); }catch(Exception e){ MessageBox.Show("Please select an account name from the Account Name dropdown."); return; } Account account = new Account { AccountName = accountName, Password = password.Text }; ValidationHelper helper = new ValidationHelper(account); if (!helper.IsValid) { MessageBox.Show(helper.Message()); return; } ISessionFactory sessionFactory = DataBaseConnection.CreateSessionFactory(); using (ISession session = sessionFactory.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Save(account); transaction.Commit(); parentForm.EnableFormOKButton(); MessageBox.Show("Account Created"); } } }
/// <summary> /// Saves exchange rates. /// </summary> private void Save() { // Check permissions CheckConfigurationModification(); string errorMessage = new Validator().NotEmpty(txtExchangeTableDisplayName.Text.Trim(), GetString("general.requiresdisplayname")).Result; if ((errorMessage == "") && (plcRateFromGlobal.Visible)) { errorMessage = new Validator().NotEmpty(txtGlobalExchangeRate.Text.Trim(), GetString("ExchangeTable_Edit.DoubleFormatRequired")).Result; } if ((errorMessage == "") && (plcRateFromGlobal.Visible)) { if (!ValidationHelper.IsPositiveNumber(txtGlobalExchangeRate.Text.Trim()) || (ValidationHelper.GetDouble(txtGlobalExchangeRate.Text.Trim(), 0) == 0)) { errorMessage = GetString("ExchangeTable_Edit.errorRate"); } } // From/to date validation if (errorMessage == "") { if ((!dtPickerExchangeTableValidFrom.IsValidRange()) || (!dtPickerExchangeTableValidTo.IsValidRange())) { errorMessage = GetString("general.errorinvaliddatetimerange"); } if ((dtPickerExchangeTableValidFrom.SelectedDateTime != DateTime.MinValue) && (dtPickerExchangeTableValidTo.SelectedDateTime != DateTime.MinValue) && (dtPickerExchangeTableValidFrom.SelectedDateTime >= dtPickerExchangeTableValidTo.SelectedDateTime)) { errorMessage = GetString("General.DateOverlaps"); } } // Exchange rates validation if (errorMessage == String.Empty) { foreach (TextBox txt in mTextBoxes.Values) { string tmp = txt.Text.Trim(); if (tmp != String.Empty) { // Exchange rate mus be double if (!ValidationHelper.IsDouble(tmp)) { errorMessage = GetString("ExchangeTable_Edit.DoubleFormatRequired"); break; } // Exchange rate must be positive double rate = ValidationHelper.GetDouble(tmp, 1); if (rate <= 0) { errorMessage = GetString("ExchangeTable_Edit.errorRate"); } } } } // Save changes if no validation error if (errorMessage == "") { // Truncate display name string displayName = txtExchangeTableDisplayName.Text.Trim().Truncate(txtExchangeTableDisplayName.MaxLength); ExchangeTableInfo exchangeTableObj = ExchangeTableInfoProvider.GetExchangeTableInfo(displayName, SiteInfoProvider.GetSiteName(ConfiguredSiteID)); // If exchangeTableName value is unique if ((exchangeTableObj == null) || (exchangeTableObj.ExchangeTableID == mExchangeTableId)) { // Get ExchangeTableInfo object by primary key exchangeTableObj = ExchangeTableInfoProvider.GetExchangeTableInfo(mExchangeTableId); if (exchangeTableObj == null) { // Create new item -> insert exchangeTableObj = new ExchangeTableInfo(); exchangeTableObj.ExchangeTableSiteID = ConfiguredSiteID; } exchangeTableObj.ExchangeTableValidFrom = dtPickerExchangeTableValidFrom.SelectedDateTime; exchangeTableObj.ExchangeTableDisplayName = displayName; exchangeTableObj.ExchangeTableValidTo = dtPickerExchangeTableValidTo.SelectedDateTime; exchangeTableObj.ExchangeTableRateFromGlobalCurrency = 0; if (plcRateFromGlobal.Visible) { exchangeTableObj.ExchangeTableRateFromGlobalCurrency = ValidationHelper.GetDouble(txtGlobalExchangeRate.Text.Trim(), 0); } // Save general exchange table information ExchangeTableInfoProvider.SetExchangeTableInfo(exchangeTableObj); // Save rates on edit if (mExchangeTableId > 0) { foreach (TextBox txt in mTextBoxes.Values) { if (mData[txt.ClientID] != null) { int rateCurrencyId = ValidationHelper.GetInteger(((DataRowView)mData[txt.ClientID])["CurrencyID"], 0); bool rateExists = mExchangeRates.ContainsKey(rateCurrencyId); if (rateExists) { ExchangeRateInfo rate = new ExchangeRateInfo(mExchangeRates[rateCurrencyId]); if (txt.Text.Trim() == String.Empty) { // Remove exchange rate ExchangeRateInfoProvider.DeleteExchangeRateInfo(rate); } else { rate.ExchangeRateValue = ValidationHelper.GetDouble(txt.Text.Trim(), 0); // Update rate ExchangeRateInfoProvider.SetExchangeRateInfo(rate); } } else { if (txt.Text.Trim() != String.Empty) { // Insert exchange rate ExchangeRateInfo rate = new ExchangeRateInfo(); rate.ExchangeRateToCurrencyID = rateCurrencyId; rate.ExchangeRateValue = ValidationHelper.GetDouble(txt.Text.Trim(), 0); rate.ExchangeTableID = mExchangeTableId; ExchangeRateInfoProvider.SetExchangeRateInfo(rate); } } } } } URLHelper.Redirect("ExchangeTable_Edit.aspx?exchangeid=" + exchangeTableObj.ExchangeTableID + "&saved=1&siteId=" + SiteID); } else { // Show error message ShowError(GetString("ExchangeTable_Edit.CurrencyNameExists")); } } else { // Show error message ShowError(errorMessage); } }
/// <summary> /// OnPreview handler. /// </summary> protected void forumEdit_OnPreview(object sender, EventArgs e) { // Preview title ltrTitle.Text = GetString("Forums_ForumNewPost_Header.Preview"); // Display placeholder plcPreview.Visible = true; // Post properties ForumPostInfo fpi = sender as ForumPostInfo; if (fpi != null) { ltrAvatar.Text = AvatarImage(fpi); ltrSubject.Text = HTMLHelper.HTMLEncode(fpi.PostSubject); ltrText.Text = ResolvePostText(fpi.PostText); ltrUserName.Text = HTMLHelper.HTMLEncode(fpi.PostUserName); ltrTime.Text = TimeZoneMethods.ConvertDateTime(fpi.PostTime, this).ToString(); BadgeInfo bi = null; string badgeName = null; string badgeImageUrl = null; bi = BadgeInfoProvider.GetBadgeInfo(MembershipContext.AuthenticatedUser.UserSettings.UserBadgeID); if (bi != null) { badgeName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(bi.BadgeDisplayName)); badgeImageUrl = HTMLHelper.HTMLEncode(bi.BadgeImageURL); } ltrBadge.Text = GetNotEmpty(badgeName, "<div class=\"Badge\">" + badgeName + "</div>", "<div class=\"Badge\">" + GetString("Forums.PublicBadge") + "</div>", ForumActionType.Badge) + GetNotEmpty(badgeImageUrl, "<div class=\"BadgeImage\"><img alt=\"" + badgeName + "\" src=\"" + GetImageUrl(ValidationHelper.GetString(badgeImageUrl, "")) + "\" /></div>", "", ForumActionType.Badge); } }
/// <summary> /// Reload data. /// </summary> public override void ReloadData() { if (ImportSettings != null) { bool singleObject = ValidationHelper.GetBoolean(ImportSettings.GetInfo(ImportExportHelper.INFO_SINGLE_OBJECT), false); chkCopyFiles.Checked = ImportSettings.CopyFiles; chkCopyCodeFiles.Checked = ImportSettings.CopyCodeFiles; chkCopyGlobalFiles.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_GLOBAL_FOLDERS), true); chkCopyAssemblies.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_ASSEMBLIES), false); chkCopySiteFiles.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_SITE_FOLDERS), true); if (SystemContext.IsPrecompiledWebsite) { // No code files or assemblies can be copied in precompiled website chkCopyAssemblies.Checked = chkCopyCodeFiles.Checked = false; chkCopyAssemblies.Enabled = chkCopyCodeFiles.Enabled = false; chkCopyAssemblies.ToolTip = chkCopyCodeFiles.ToolTip = GetString("importobjects.copyfiles.disabled"); } chkBindings.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_ADD_SITE_BINDINGS), true); chkDeleteSite.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_DELETE_SITE), false); chkRunSite.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_RUN_SITE), !singleObject); bool?updateSiteDefinition = ImportSettings.GetSettings(ImportExportHelper.SETTINGS_UPDATE_SITE_DEFINITION); // Disable checkbox if value is already explicitly set to false if (updateSiteDefinition == false) { chkUpdateSite.Enabled = false; chkUpdateSite.Checked = false; } else { chkUpdateSite.Checked = ValidationHelper.GetBoolean(updateSiteDefinition, !singleObject); } chkSkipOrfans.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_SKIP_OBJECT_ON_TRANSLATION_ERROR), false); chkImportTasks.Checked = ValidationHelper.GetBoolean(ImportSettings.GetSettings(ImportExportHelper.SETTINGS_TASKS), true); chkLogSync.Checked = ImportSettings.LogSynchronization; chkLogInt.Checked = ImportSettings.LogIntegration; chkRebuildIndexes.Checked = ImportSettings.SiteIsIncluded; chkRebuildIndexes.Visible = ImportSettings.SiteIsIncluded; Visible = true; if (ImportSettings.TemporaryFilesCreated) { if (ImportSettings.SiteIsIncluded && !singleObject) { plcSite.Visible = true; if (ImportSettings.ExistingSite) { plcExistingSite.Visible = true; chkUpdateSite.Text = GetString("ImportObjects.UpdateSite"); } plcSiteFiles.Visible = true; chkBindings.Text = GetString("ImportObjects.Bindings"); chkRunSite.Text = GetString("ImportObjects.RunSite"); chkDeleteSite.Text = GetString("ImportObjects.DeleteSite"); } else { plcSite.Visible = false; } } } else { Visible = false; } }
public IEnumerator Validate(object projectSystem) { return(ValidationHelper.Validate(this, false).ToArray().GetEnumerator()); }
protected void Page_Load(object sender, EventArgs e) { CopyValues(forumEdit); if (IsAdHocForum) { plcHeader.Visible = false; } forumEdit.OnPreview += forumEdit_OnPreview; forumEdit.OnModerationRequired += new EventHandler(forumEdit_OnModerationRequired); // Check whether subscription is for forum or post if (ForumContext.CurrentReplyThread == null) { ltrTitle.Text = GetString("Forums_ForumNewPost_Header.NewThread"); if (ForumContext.CurrentPost != null && ForumContext.CurrentMode == ForumMode.Edit) { ltrTitle.Text = GetString("Forums_ForumNewPost_Header.EditPost"); } } else { plcPreview.Visible = true; ltrTitle.Text = GetString("Forums_ForumNewPost_Header.Reply"); ltrAvatar.Text = AvatarImage(ForumContext.CurrentReplyThread); ltrSubject.Text = HTMLHelper.HTMLEncode(ForumContext.CurrentReplyThread.PostSubject); ltrText.Text = ResolvePostText(ForumContext.CurrentReplyThread.PostText); ltrUserName.Text = HTMLHelper.HTMLEncode(ForumContext.CurrentReplyThread.PostUserName); ltrTime.Text = TimeZoneMethods.ConvertDateTime(ForumContext.CurrentReplyThread.PostTime, this).ToString(); UserSettingsInfo usi = UserSettingsInfoProvider.GetUserSettingsInfoByUser(ForumContext.CurrentReplyThread.PostUserID); BadgeInfo bi = null; string badgeName = null; string badgeImageUrl = null; if (usi != null) { bi = BadgeInfoProvider.GetBadgeInfo(usi.UserBadgeID); if (bi != null) { badgeName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(bi.BadgeDisplayName)); badgeImageUrl = HTMLHelper.HTMLEncode(bi.BadgeImageURL); } } ltrBadge.Text = GetNotEmpty(badgeName, "<div class=\"Badge\">" + badgeName + "</div>", "<div class=\"Badge\">" + GetString("Forums.PublicBadge") + "</div>", ForumActionType.Badge) + GetNotEmpty(badgeImageUrl, "<div class=\"BadgeImage\"><img alt=\"" + badgeName + "\" src=\"" + GetImageUrl(ValidationHelper.GetString(badgeImageUrl, "")) + "\" /></div>", "", ForumActionType.Badge); } }
/// <summary> /// Archives document(s). /// </summary> private void ArchiveAll(object parameter) { if (parameter == null) { return; } TreeProvider tree = new TreeProvider(currentUser); tree.AllowAsyncActions = false; try { // Begin log AddLog(ResHelper.GetString("content.archivingdocuments", currentCulture)); string[] parameters = ((string)parameter).Split(';'); string siteName = parameters[1]; // Get identifiers int[] workNodes = nodeIds.ToArray(); // Prepare the where condition string where = new WhereCondition().WhereIn("NodeID", workNodes).ToString(true); string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture"); // Get cultures string cultureCode = chkAllCultures.Checked ? TreeProvider.ALL_CULTURES : parameters[0]; // Get the documents DataSet documents = tree.SelectNodes(siteName, "/%", cultureCode, false, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns); // Create instance of workflow manager class WorkflowManager wm = WorkflowManager.GetInstance(tree); if (!DataHelper.DataSourceIsEmpty(documents)) { foreach (DataRow nodeRow in documents.Tables[0].Rows) { // Get the current document string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); TreeNode node = GetDocument(tree, siteName, nodeRow); if (PerformArchive(wm, node, aliasPath)) { return; } // Process underlying documents if (chkUnderlying.Checked && node.NodeHasChildren && ArchiveSubDocuments(node, tree, wm, cultureCode, siteName)) { return; } } } else { AddError(ResHelper.GetString("content.nothingtoarchive", currentCulture)); } } catch (ThreadAbortException ex) { if (!CMSThread.Stopped(ex)) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.archivefailed", currentCulture), ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.archivefailed", currentCulture), ex); } }
public void ValidationHelper_GetValidationsCC_Success_Test() { // Assemble var valHelper = new ValidationHelper(); // Act var vals = valHelper.GetValidations("TestDTO.ValidationTest", "model", null, true, "Intertech.Validation.Test"); // Assert Assert.IsNotNull(vals); AssertJsonEqual(_validationsCC, vals); }
/// <summary> /// Loads control parameters. /// </summary> private void LoadParameters() { string identifier = QueryHelper.GetString("params", null); parameters = (Hashtable)WindowHelper.GetItem(identifier); if (parameters != null) { ResourcePrefix = ValidationHelper.GetString(parameters["ResourcePrefix"], null); // Load values from session selectionMode = (SelectionModeEnum)parameters["SelectionMode"]; objectType = ValidationHelper.GetString(parameters["ObjectType"], null); returnColumnName = ValidationHelper.GetString(parameters["ReturnColumnName"], null); valuesSeparator = ValidationHelper.GetValue(parameters["ValuesSeparator"], ';'); filterControl = ValidationHelper.GetString(parameters["FilterControl"], null); useDefaultNameFilter = ValidationHelper.GetBoolean(parameters["UseDefaultNameFilter"], true); whereCondition = ValidationHelper.GetString(parameters["WhereCondition"], null); orderBy = ValidationHelper.GetString(parameters["OrderBy"], null); itemsPerPage = ValidationHelper.GetInteger(parameters["ItemsPerPage"], 10); emptyReplacement = ValidationHelper.GetString(parameters["EmptyReplacement"], " "); dialogGridName = ValidationHelper.GetString(parameters["DialogGridName"], dialogGridName); additionalColumns = ValidationHelper.GetString(parameters["AdditionalColumns"], null); callbackMethod = ValidationHelper.GetString(parameters["CallbackMethod"], null); allowEditTextBox = ValidationHelper.GetBoolean(parameters["AllowEditTextBox"], false); fireOnChanged = ValidationHelper.GetBoolean(parameters["FireOnChanged"], false); disabledItems = ";" + ValidationHelper.GetString(parameters["DisabledItems"], String.Empty) + ";"; GlobalObjectSuffix = ValidationHelper.GetString(parameters["GlobalObjectSuffix"], string.Empty); AddGlobalObjectSuffix = ValidationHelper.GetBoolean(parameters["AddGlobalObjectSuffix"], false); AddGlobalObjectNamePrefix = ValidationHelper.GetBoolean(parameters["AddGlobalObjectNamePrefix"], false); RemoveMultipleCommas = ValidationHelper.GetBoolean(parameters["RemoveMultipleCommas"], false); filterMode = ValidationHelper.GetString(parameters["FilterMode"], null); displayNameFormat = ValidationHelper.GetString(parameters["DisplayNameFormat"], null); additionalSearchColumns = ValidationHelper.GetString(parameters["AdditionalSearchColumns"], String.Empty); siteWhereCondition = ValidationHelper.GetString(parameters["SiteWhereCondition"], null); UseTypeCondition = ValidationHelper.GetBoolean(parameters["UseTypeCondition"], true); AllowLocalizedFiltering = ValidationHelper.GetBoolean(parameters["AllowLocalizedFiltering"], true); mZeroRowsText = ValidationHelper.GetString(parameters["ZeroRowsText"], string.Empty); mFilteredZeroRowsText = ValidationHelper.GetString(parameters["FilteredZeroRowsText"], string.Empty); mHasDependingFields = ValidationHelper.GetBoolean(parameters["HasDependingFields"], false); // Custom parameter loaded from session as i can't seem to append my data to the HashTable toolTipFormat = ValidationHelper.GetString(SessionHelper.GetValue("ToolTipFormat_" + identifier), ""); // Set item prefix if it was passed by UniSelector's AdditionalUrlParameters var itemPrefix = QueryHelper.GetString("ItemPrefix", null); if (!String.IsNullOrEmpty(itemPrefix)) { ItemPrefix = itemPrefix; } // Init object if (!string.IsNullOrEmpty(objectType)) { iObjectType = ModuleManager.GetReadOnlyObject(objectType); if (iObjectType == null) { throw new Exception("[UniSelector.SelectionDialog]: Object type '" + objectType + "' not found."); } if (returnColumnName == null) { returnColumnName = iObjectType.TypeInfo.IDColumn; } } // Pre-select unigrid values passed from parent window if (!RequestHelper.IsPostBack()) { string values = (string)parameters["Values"]; if (!String.IsNullOrEmpty(values)) { hidItem.Value = values; parameters["Values"] = null; } } } }
/// <summary> /// Unigrid external data bound handler. /// </summary> protected object uniGrid_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLowerInvariant()) { case "yesno": return(UniGridFunctions.ColoredSpanYesNo(parameter)); case "select": { var ti = iObjectType.TypeInfo; DataRowView drv = (DataRowView)parameter; // Get item ID string itemID = drv[returnColumnName].ToString(); // Add global object name prefix if required if (AddGlobalObjectNamePrefix && HasSiteIdColumn(ti) && (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) == 0)) { itemID = "." + itemID; } // Add checkbox for multiple selection switch (selectionMode) { case SelectionModeEnum.Multiple: case SelectionModeEnum.MultipleTextBox: case SelectionModeEnum.MultipleButton: { var itemWithSeparators = string.Format("{0}{1}{0}", valuesSeparator, itemID); string checkBox = string.Format("<span class=\"checkbox\"><input id=\"chk{0}\" type=\"checkbox\" onclick=\"ProcessItem(this,false); UpdateCheckboxAllElement();\" class=\"chckbox\" ", itemID); if (hidItem.Value.IndexOf(itemWithSeparators, StringComparison.OrdinalIgnoreCase) >= 0) { checkBox += "checked=\"checked\" "; } else { allRowsChecked = false; } if (disabledItems.Contains(itemWithSeparators)) { checkBox += "disabled=\"disabled\" "; } checkBox += string.Format("/><label for=\"chk{0}\"> </label></span>", itemID); return(checkBox); } } } break; case "itemname": { DataRowView drv = (DataRowView)parameter; // Get item ID string itemID = drv[returnColumnName].ToString(); // Get item name string itemName; // Special formatted user name if (displayNameFormat == UniSelector.USER_DISPLAY_FORMAT) { string userName = DataHelper.GetStringValue(drv.Row, "UserName"); string fullName = DataHelper.GetStringValue(drv.Row, "FullName"); itemName = Functions.GetFormattedUserName(userName, fullName, IsLiveSite); } else if (displayNameFormat == null) { itemName = drv[iObjectType.DisplayNameColumn].ToString(); } else { MacroResolver resolver = MacroResolver.GetInstance(); foreach (DataColumn item in drv.Row.Table.Columns) { resolver.SetNamedSourceData(item.ColumnName, drv.Row[item.ColumnName]); } itemName = resolver.ResolveMacros(displayNameFormat); } if (RemoveMultipleCommas) { itemName = TextHelper.RemoveMultipleCommas(itemName); } // Add the prefixes itemName = ItemPrefix + itemName; itemID = ItemPrefix + itemID; var ti = iObjectType.TypeInfo; // Add global object name prefix if required if (AddGlobalObjectNamePrefix && HasSiteIdColumn(ti) && (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) == 0)) { itemID = "." + itemID; } if (String.IsNullOrEmpty(itemName)) { itemName = emptyReplacement; } if (AddGlobalObjectSuffix && HasSiteIdColumn(ti)) { itemName += (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) > 0 ? string.Empty : " " + GlobalObjectSuffix); } // Link action string onclick = null; bool disabled = disabledItems.Contains(";" + itemID + ";"); if (!disabled) { string safeItemID = GetSafe(itemID); string itemHash = ValidationHelper.GetHashString(itemID, new HashSettings(ClientID)); switch (selectionMode) { case SelectionModeEnum.Multiple: case SelectionModeEnum.MultipleTextBox: case SelectionModeEnum.MultipleButton: onclick = string.Format("ProcessItem(document.getElementById('chk{0}'),true); UpdateCheckboxAllElement(); return false;", ScriptHelper.GetString(itemID).Trim('\'')); break; case SelectionModeEnum.SingleButton: onclick = string.Format("SelectItems({0},'{1}'); return false;", safeItemID, itemHash); break; case SelectionModeEnum.SingleTextBox: if (allowEditTextBox) { if (!mHasDependingFields) { onclick = string.Format("SelectItems({0},{0},{1},{2},{3},'{4}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash); } else { onclick = string.Format("SelectItemsReload({0},{0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash); } } else { if (!mHasDependingFields) { onclick = string.Format("SelectItems({0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash); } else { onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash); } } break; default: onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash); break; } onclick = "onclick=\"" + onclick + "\" "; } if (LocalizeItems) { itemName = ResHelper.LocalizeString(itemName); } // Custom Tooltip string tooltip = ""; if (!string.IsNullOrWhiteSpace(toolTipFormat)) { MacroResolver resolver = MacroResolver.GetInstance(); foreach (DataColumn item in drv.Row.Table.Columns) { resolver.SetNamedSourceData(item.ColumnName, drv.Row[item.ColumnName]); } tooltip = resolver.ResolveMacros(toolTipFormat); } if (!string.IsNullOrWhiteSpace(tooltip)) { tooltip = "title=\"" + CMS.Helpers.HTMLHelper.EncodeForHtmlAttribute(tooltip) + "\" "; } return("<div " + (!disabled ? "class=\"SelectableItem\" " : null) + onclick + tooltip + ">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(itemName, 100)) + "</div>"); } } return(null); }
// // This is the static internal callback that will be called when // the IO we issued for the user to winsock has completed, either // synchronously (Signaled=false) or asynchronously (Signaled=true) // when this function gets called it must: // 1) update the AsyncResult object with the results of the completed IO // 2) signal events that the user might be waiting on // 3) cal the callback function that the user might have specified // internal static void ConnectCallback(object stateObject, bool Signaled) { ConnectAsyncResult asyncResult = stateObject as ConnectAsyncResult; Socket socket = asyncResult.AsyncObject as Socket; GlobalLog.Enter("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback", "Signaled:" + Signaled.ToString()); GlobalLog.Assert(!asyncResult.IsCompleted, "Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() asyncResult.IsCompleted", ""); // // // get async completion // /* * int errorCode = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); * GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() GetSocketOption() returns errorCode:" + errorCode.ToString()); */ NetworkEvents networkEvents = new NetworkEvents(); networkEvents.Events = AsyncEventBits.FdConnect; AutoResetEvent chkAsyncEvent = socket.m_AsyncEvent; int errorCode = SocketErrors.WSAENOTSOCK; if (chkAsyncEvent != null) { errorCode = UnsafeNclNativeMethods.OSSOCK.WSAEnumNetworkEvents( socket.m_Handle, chkAsyncEvent.Handle, ref networkEvents); if (errorCode != SocketErrors.Success) { errorCode = Marshal.GetLastWin32Error(); GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() WSAEnumNetworkEvents() failed with errorCode:" + errorCode.ToString()); } else { errorCode = networkEvents.ErrorCodes[(int)AsyncEventBitsPos.FdConnectBit]; GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() ErrorCodes(FdConnect) got errorCode:" + errorCode.ToString()); } } try { // // cancel async event // socket.SetAsyncEventSelect(AsyncEventBits.FdNone); // // go back to blocking mode // socket.InternalSetBlocking(true); } catch (Exception exception) { GlobalLog.Print("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback() caught exception::" + exception.Message); asyncResult.Result = exception; } // // if the native non-blocking call failed we'll throw a SocketException in EndConnect() // if (errorCode != SocketErrors.Success) { // // just save the error code, the SocketException will be thrown in EndConnect() // asyncResult.ErrorCode = errorCode; } else { // // the Socket is connected, update our state and performance counter // socket.SetToConnected(); } // // call the user's callback now, if there is one. // asyncResult.InvokeCallback(false); GlobalLog.Leave("Socket#" + ValidationHelper.HashString(socket) + "::ConnectCallback", errorCode.ToString()); }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { ShowError("general.modifynotallowed"); return(false); } } // Save the data if ((pi != null) && (pti != null) && (templateInstance != null) && SaveForm(formCustom)) { // Check manage permission for non-livesite version if ((CMSContext.ViewMode != ViewModeEnum.LiveSite) && (CMSContext.ViewMode != ViewModeEnum.DashboardWidgets)) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(pi.NodeId, pi.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { return(false); } } // Get the zone zone = templateInstance.EnsureZone(ZoneId); if (zone != null) { zone.WidgetZoneType = zoneType; // Add new widget if (IsNewWidget) { AddWidget(); } if (IsNewVariant) { widgetInstance = widgetInstance.Clone(); if (pi.DocumentTemplateInstance.WebPartZones.Count == 0) { // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(pi.DocumentId, tree); // Extract and set the document web parts node.SetValue("DocumentWebParts", templateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, tree); } } // Get basicform's datarow and update widget SaveFormToWidget(formCustom); if (IsNewVariant) { // Ensures unique id for new widget variant widgetInstance.ControlID = WebPartZoneInstance.GetUniqueWebPartId(wi.WidgetName, zone.ParentTemplateInstance); } // Allow set dashboard in design mode if ((zoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, pti, templateInstance, zoneType, CMSContext.ViewMode, tree); } else if ((CMSContext.ViewMode == ViewModeEnum.Edit) && (zoneType == WidgetZoneTypeEnum.Editor)) { // Save the variant properties if ((widgetInstance != null) && (widgetInstance.ParentZone != null) && (widgetInstance.ParentZone.ParentTemplateInstance != null) && (widgetInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate != null)) { string variantName = string.Empty; string variantDisplayName = string.Empty; string variantDisplayCondition = string.Empty; string variantDescription = string.Empty; bool variantEnabled = true; string zoneId = widgetInstance.ParentZone.ZoneID; int templateId = widgetInstance.ParentZone.ParentTemplateInstance.ParentPageTemplate.PageTemplateId; Guid instanceGuid = Guid.Empty; XmlDocument doc = new XmlDocument(); XmlNode xmlWebParts = null; xmlWebParts = widgetInstance.GetXmlNode(doc); instanceGuid = InstanceGUID; Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { variantName = ValidationHelper.GetString(properties["codename"], string.Empty); variantDisplayName = ValidationHelper.GetString(properties["displayname"], string.Empty); variantDescription = ValidationHelper.GetString(properties["description"], string.Empty); variantEnabled = ValidationHelper.GetBoolean(properties["enabled"], true); if (VariantMode == VariantModeEnum.ContentPersonalization) { variantDisplayCondition = ValidationHelper.GetString(properties["condition"], string.Empty); } } // Save the web part variant properties if (VariantMode == VariantModeEnum.MVT) { ModuleCommands.OnlineMarketingSaveMVTVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, zoneId, widgetInstance.InstanceGUID, templateId, pi.DocumentId, xmlWebParts); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { ModuleCommands.OnlineMarketingSaveContentPersonalizationVariant(VariantID, variantName, variantDisplayName, variantDescription, variantEnabled, variantDisplayCondition, zoneId, widgetInstance.InstanceGUID, templateId, pi.DocumentId, xmlWebParts); } // Clear the document template templateInstance.ParentPageTemplate.ParentPageInfo.DocumentTemplateInstance = null; // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(pi.DocumentId, tree); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Clear the cached web part if (InstanceGUID != null) { CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLower()); } return(true); } return(false); }
/// <summary> /// Init event handler. /// </summary> protected override void OnInit(EventArgs e) { base.OnInit(e); // Setup basic form on live site formCustom.AllowMacroEditing = false; formCustom.IsLiveSite = IsLiveSite; // Load settings if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Try to find the widget variant in the database and set its VariantID if (IsNewVariant) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(properties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = 0; if (VariantMode == VariantModeEnum.MVT) { variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName); } // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } EnsureDashboard(); if (!String.IsNullOrEmpty(WidgetId) && !IsInline) { // Get pageinfo try { pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId); } catch (PageNotFoundException) { // Do not throw exception if page info not found (e.g. bad alias path) } if (pi == null) { lblInfo.Text = GetString("Widgets.Properties.aliasnotfound"); lblInfo.Visible = true; pnlFormArea.Visible = false; return; } // Get template pti = pi.PageTemplateInfo; // Get template instance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); if (!IsNewWidget) { // Get the instance of widget widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetId); if (widgetInstance == null) { lblInfo.Text = GetString("Widgets.Properties.WidgetNotFound"); lblInfo.Visible = true; pnlFormArea.Visible = false; return; } if ((VariantID > 0) && (widgetInstance != null) && (widgetInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { widgetInstance = pi.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId); widgetInstance = widgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID)); // Set the widget variant mode if (widgetInstance != null) { VariantMode = widgetInstance.VariantMode; } } else { // Not authorised for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } // Get widget info by widget name(widget type) wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType); } // Widget instance hasn't created yet else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } CMSPage.EditedObject = wi; zoneType = ZoneType; // Get the zone to which it inserts WebPartZoneInstance zone = templateInstance.GetZone(ZoneId); if ((zoneType == WidgetZoneTypeEnum.None) && (zone != null)) { zoneType = zone.WidgetZoneType; } // Check security CurrentUserInfo currentUser = CMSContext.CurrentUser; switch (zoneType) { // Group zone => Only group widgets and group admin case WidgetZoneTypeEnum.Group: // Should always be, only group widget are allowed in group zone if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupId) && ((CMSContext.ViewMode != ViewModeEnum.Design) || ((CMSContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design")))))) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for editor zones case WidgetZoneTypeEnum.Editor: if (!wi.WidgetForEditor) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for user zones case WidgetZoneTypeEnum.User: if (!wi.WidgetForUser) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for dasboard zones case WidgetZoneTypeEnum.Dashboard: if (!wi.WidgetForDashboard) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; } // Check security if ((zoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated())) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } // Get form schemas wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); FormInfo zoneTypeDefinition = PortalHelper.GetPositionFormInfo(zoneType); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo fi = FormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true); if (fi != null) { // Check if there are some editable properties FormFieldInfo[] ffi = fi.GetFields(true, false); if ((ffi == null) || (ffi.Length == 0)) { lblInfo.Visible = true; lblInfo.Text = GetString("widgets.emptyproperties"); } // Get datarows with required columns DataRow dr = CombineWithDefaultValues(fi, wi); // Load default values for new widget if (IsNewWidget) { fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); // Overide default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(wi.WidgetDisplayName)); } // Load values from existing widget LoadDataRowFromWidget(dr); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES; } } if (IsInline) { //Load text definition from session string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty); if (String.IsNullOrEmpty(definition)) { definition = Request.Form[hdnWidgetDefinition.UniqueID]; } else { hdnWidgetDefinition.Value = definition; } Hashtable parameters = null; if (IsNewWidget) { // new wdiget - load widget info by id if (!String.IsNullOrEmpty(WidgetId)) { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } else { // Try to get widget from codename mName = QueryHelper.GetString("WidgetName", String.Empty); wi = WidgetInfoProvider.GetWidgetInfo(mName); } } else { if (definition == null) { ShowError("widget.failedtoload"); return; } //parse defininiton parameters = CMSDialogHelper.GetHashTableFromString(definition); //trim control name if (parameters["name"] != null) { mName = parameters["name"].ToString(); } wi = WidgetInfoProvider.GetWidgetInfo(mName); } if (wi == null) { ShowError("widget.failedtoload"); return; } //If widget cant be used asi inline if (!wi.WidgetForInline) { ShowError("widget.cantbeusedasinline"); return; } //Test permission for user CurrentUserInfo currentUser = CMSContext.CurrentUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated())) { mIsValidWidget = false; OnNotAllowed(this, null); } //If user is editor, more properties are shown WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User; if (currentUser.IsEditor) { zoneType = WidgetZoneTypeEnum.Editor; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo zoneTypeDefinition = PortalHelper.GetPositionFormInfo(zoneType); FormInfo fi = FormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true); if (fi != null) { // Check if there are some editable properties mFields = fi.GetFields(true, true); if ((mFields == null) || (mFields.Length == 0)) { lblInfo.Visible = true; lblInfo.Text = GetString("widgets.emptyproperties"); } // Get datarows with required columns DataRow dr = CombineWithDefaultValues(fi, wi); if (IsNewWidget) { // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); } else { foreach (string key in parameters.Keys) { string value = parameters[key].ToString(); // Test if given property exists if (dr.Table.Columns.Contains(key) && !String.IsNullOrEmpty(value)) { try { dr[key] = value; } catch { } } } } // Overide default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES; } } }
/// <summary> /// Saves the given DataRow data to the web part properties. /// </summary> /// <param name="form">Form to save</param> private void SaveFormToWidget(BasicForm form) { if (form.Visible && (widgetInstance != null)) { // Keep the old ID to check the change of the ID string oldId = widgetInstance.ControlID.ToLowerInvariant(); DataRow dr = form.DataRow; // Load default values for new widget if (IsNewWidget) { form.FormInformation.LoadDefaultValues(dr, wi.WidgetDefaultValues); } foreach (DataColumn column in dr.Table.Columns) { widgetInstance.MacroTable[column.ColumnName.ToLower()] = form.MacroTable[column.ColumnName.ToLower()]; widgetInstance.SetValue(column.ColumnName, dr[column]); // If name changed, move the content if (String.Compare(column.ColumnName, "widgetcontrolid", StringComparison.InvariantCultureIgnoreCase) == 0) { try { string newId = ValidationHelper.GetString(dr[column], "").ToLowerInvariant(); // Name changed if (!String.IsNullOrEmpty(newId) && (String.Compare(newId, oldId, false) != 0)) { mWidgetIdChanged = true; WidgetId = newId; // Move the document content if present string currentContent = (string)(pi.EditableWebParts[oldId]); if (currentContent != null) { TreeNode node = DocumentHelper.GetDocument(pi.DocumentId, tree); // Move the content in the page info pi.EditableWebParts[oldId] = null; pi.EditableWebParts[newId] = currentContent; // Update the document node.SetValue("DocumentContent", pi.GetContentXml()); DocumentHelper.UpdateDocument(node, tree); } // Change the underlying zone names if layout web part if ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout)) { string prefix = oldId + "_"; foreach (WebPartZoneInstance zone in pti.WebPartZones) { if (zone.ZoneID.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)) { // Change the zone prefix to the new one zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length)); } } } } } catch (Exception ex) { EventLogProvider ev = new EventLogProvider(); ev.LogEvent("Content", "CHANGEWIDGET", ex); } } } } }
public void ValidationHelper_GetValidations_DTONotFound_Test() { // Assemble var valHelper = new ValidationHelper(); // Act var vals = valHelper.GetValidations("blah", "model", null, false, "Intertech.Validation.Test"); // Assert Assert.IsNull(vals); }
public void ValidationHelper_GetValidations_Success_ParmsObject_Test() { // Assemble var valHelper = new ValidationHelper(); // Act var vals = valHelper.GetValidations(_parms); // Assert Assert.IsNotNull(vals); AssertJsonEqual(_validations, vals); }
object Grid_OnExternalDataBound(object sender, string sourceName, object parameter) { int chatUserID = ValidationHelper.GetInteger(parameter, 0); string name = sourceName.ToLowerCSafe(); switch (name) { case "chatroomuserchatuserid": ChatUserInfo user = ChatUserInfoProvider.GetChatUserInfo(chatUserID); return(ChatUIHelper.GetCMSDeskChatUserField(this, user)); case "adminlevel": AdminLevelEnum adminLevel = (AdminLevelEnum)parameter; return(adminLevel.ToStringValue()); case "onlinestatus": if (parameter == DBNull.Value) { parameter = null; } DateTime?joinTime = (DateTime?)parameter; string input = "<span class=\"{0}\">{1}</span>"; return(String.Format(input, (joinTime.HasValue) ? "StatusEnabled" : "StatusDisabled", GetString(joinTime.HasValue ? "general.yes" : "general.no"))); case "action_kick": case "action_revoke": case "action_edit": //Gets the value of the UserName column from the current data row DataRow row = ((DataRowView)((GridViewRow)parameter).DataItem).Row; bool visible = true; CMSGridActionButton actionButton = (CMSGridActionButton)sender; // Can't perform any action in one to one support room if (ChatRoom.IsOneToOneSupport) { visible = false; } else { if (name == "action_kick") { if (row["ChatRoomUserJoinTime"] == DBNull.Value) { visible = false; } actionButton.IconCssClass = "icon-arrow-right-rect"; } else if (name == "action_revoke") { // Can't revoke access to the creator of the room // Can't revoke access to the public room if (!ChatRoom.ChatRoomPrivate || ((int)row["ChatRoomUserAdminLevel"] == (int)AdminLevelEnum.Creator)) { visible = false; } actionButton.IconCssClass = "icon-times-circle color-red-70"; } else if (name == "action_edit") { actionButton.IconCssClass = "icon-edit"; actionButton.IconStyle = GridIconStyle.Allow; } } if (!visible) { actionButton.Visible = false; } else if (!HasUserModifyPermission) { actionButton.Enabled = false; } break; } return(parameter); }
private void updateIndigene() { ISessionFactory sessionFactory = DataBaseConnection.CreateSessionFactory(); using (ISession session = sessionFactory.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { try { indigene.FirstName = name.Text.Substring(0, name.Text.IndexOf(" ")).Trim(); indigene.OtherNames = name.Text.Substring(name.Text.IndexOf(" ")).Trim(); indigene.Village = village.SelectedItem.ToString().Trim(); indigene.MaritalStatus = maritalstatus.SelectedItem.ToString().Trim(); indigene.Sex = sexComboBox.SelectedItem.ToString().Trim(); indigene.DateOfBirth = (DateTime)dateofbirthDatePicker.SelectedDate; indigene.NameOfParents = nameofParents.Text.Trim(); indigene.Occupation = occupation.Text.Trim(); indigene.PhoneNumber = phoneNumber.Text.Trim(); indigene.PlaceOfResidence = placeofResidence.Text.Trim(); indigene.Comments = comments.Text.Trim(); } catch (Exception ex) { parentWindow.ShowDialog("Some fields are empty, please fill them and then re-submit", true); return; } ValidationHelper validationHelper = new ValidationHelper(indigene); if (!validationHelper.IsValid) { parentWindow.ShowDialog(validationHelper.Message(), true); } else { foreach (var child in indigene.Children) { indigene.AddChild(child); //session.SaveOrUpdate(child); } session.Update(indigene); transaction.Commit(); parentWindow.ShowDialog("Indigene information Updated", true); parentWindow.IndigeneUpdate(); } } } }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (!UserName.IsNullOrEmpty()) { if (!UserName.Equals(EmailAddress, StringComparison.OrdinalIgnoreCase) && ValidationHelper.IsEmail(UserName)) { yield return new ValidationResult("Username cannot be an email address unless it's same with your email address !"); } } }
internal HtmlHelper(ModelStateDictionary modelState, ValidationHelper validationHelper) { ModelState = modelState; _validationHelper = validationHelper; }
/// <summary> /// Performs necessary checks and publishes document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformPublish(WorkflowManager wm, TreeProvider tree, string siteName, DataRow nodeRow) { string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); return(PerformPublish(wm, GetDocument(tree, siteName, nodeRow), aliasPath)); }
protected void Page_Load(object sender, EventArgs e) { // Register main CMS script file ScriptHelper.RegisterCMS(this); if (QueryHelper.ValidateHash("hash") && (Parameters != null)) { // Initialize current user currentUser = MembershipContext.AuthenticatedUser; // Check permissions if (!currentUser.IsGlobalAdministrator && !currentUser.IsAuthorizedPerResource("CMS.Content", "manageworkflow")) { RedirectToAccessDenied("CMS.Content", "manageworkflow"); } // Set current UI culture currentCulture = CultureHelper.PreferredUICultureCode; // Initialize current site currentSiteName = SiteContext.CurrentSiteName; currentSiteId = SiteContext.CurrentSiteID; // Initialize events ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished; ctlAsyncLog.OnError += ctlAsyncLog_OnError; ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel; if (!RequestHelper.IsCallback()) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(currentUser); // Current Node ID to delete string parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty); if (string.IsNullOrEmpty(parentAliasPath)) { // Get IDs of nodes string nodeIdsString = ValidationHelper.GetString(Parameters["nodeids"], string.Empty); string[] nodeIdsArr = nodeIdsString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } } else { var where = new WhereCondition(WhereCondition) .WhereNotEquals("ClassName", SystemDocumentTypes.Root); string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName,DocumentCheckedOutByUserID"); allDocs = tree.SelectNodes(currentSiteName, parentAliasPath.TrimEnd('/') + "/%", TreeProvider.ALL_CULTURES, true, DataClassInfoProvider.GetClassName(ClassID), where.ToString(true), "DocumentName", 1, false, 0, columns); if (!DataHelper.DataSourceIsEmpty(allDocs)) { foreach (DataRow row in allDocs.Tables[0].Rows) { nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0)); } } } // Initialize strings based on current action string titleText = null; switch (CurrentAction) { case WorkflowAction.Archive: headQuestion.ResourceString = "content.archivequestion"; chkAllCultures.ResourceString = "content.archiveallcultures"; chkUnderlying.ResourceString = "content.archiveunderlying"; canceledString = GetString("content.archivecanceled"); // Setup title of log ctlAsyncLog.TitleText = GetString("content.archivingdocuments"); // Setup page title text and image titleText = GetString("Content.ArchiveTitle"); break; case WorkflowAction.Publish: headQuestion.ResourceString = "content.publishquestion"; chkAllCultures.ResourceString = "content.publishallcultures"; chkUnderlying.ResourceString = "content.publishunderlying"; canceledString = GetString("content.publishcanceled"); // Setup title of log ctlAsyncLog.TitleText = GetString("content.publishingdocuments"); // Setup page title text and image titleText = GetString("Content.PublishTitle"); break; } PageTitle.TitleText = titleText; EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText); if (nodeIds.Count == 0) { // Hide if no node was specified pnlContent.Visible = false; return; } // Register the dialog script ScriptHelper.RegisterDialogScript(this); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; // Set all cultures checkbox DataSet culturesDS = CultureSiteInfoProvider.GetSiteCultures(currentSiteName); if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1)) { chkAllCultures.Checked = true; plcAllCultures.Visible = false; } if (nodeIds.Count > 0) { pnlDocList.Visible = true; // Create where condition string where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true); string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName,DocumentCheckedOutByUserID"); // Select nodes DataSet ds = allDocs ?? tree.SelectNodes(currentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", TreeProvider.ALL_LEVELS, false, 0, columns); // Enumerate selected documents if (!DataHelper.DataSourceIsEmpty(ds)) { cancelNodeId = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID"); foreach (DataRow dr in ds.Tables[0].Rows) { AddToList(dr); } // Display enumeration of documents foreach (KeyValuePair <int, string> line in list) { lblDocuments.Text += line.Value; } } } } // Set title for dialog mode string title = GetString("general.publish"); if (CurrentAction == WorkflowAction.Archive) { title = GetString("general.archive"); } SetTitle(title); } else { pnlPublish.Visible = false; ShowError(GetString("dialogs.badhashtext")); } }
public void Validate_MultipleRulesForSameTarget_ClearsResultsBeforeValidation() { // ARRANGE var validation = new ValidationHelper(); var dummy = new DummyViewModel(); RuleResult firstRuleResult = RuleResult.Valid(); RuleResult secondRuleResult = RuleResult.Invalid("Error2"); validation.AddRule(() => dummy.Foo, () => { return firstRuleResult; }); validation.AddRule(() => dummy.Foo, () => { return secondRuleResult; }); // ACT validation.ValidateAll(); firstRuleResult = RuleResult.Invalid("Error1"); validation.ValidateAll(); // VERIFY var result = validation.GetResult(() => dummy.Foo); Assert.False(result.IsValid); Assert.Equal(1, result.ErrorList.Count); Assert.Equal("Error1", result.ErrorList[0].ErrorText); }
protected void uniSelector_OnSelectionChanged(object sender, EventArgs e) { bool relaodNeeded = false; // Remove old items string newValues = ValidationHelper.GetString(this.uniSelector.Value, null); string items = DataHelper.GetNewItemsInList(newValues, currentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Initialize tree provider TreeProvider tree = new TreeProvider(); // Add all new items to site foreach (string item in newItems) { string cultureCode = ValidationHelper.GetString(item, ""); // Get the documents assigned to the culture being removed DataSet nodes = tree.SelectNodes(siteName, "/%", cultureCode, false, null, null, null, -1, false); if (DataHelper.DataSourceIsEmpty(nodes)) { CultureInfoProvider.RemoveCultureFromSite(cultureCode, siteName); } else { relaodNeeded = true; this.lblError.Visible = true; this.lblError.Text += String.Format(GetString("site_edit_cultures.errorremoveculturefromsite"), cultureCode) + '\n'; } } } } // Catch license limitations Exception try { // Add new items items = DataHelper.GetNewItemsInList(currentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to site foreach (string item in newItems) { string cultureCode = ValidationHelper.GetString(item, ""); CultureInfoProvider.AddCultureToSite(cultureCode, siteName); } } } } catch (Exception ex) { relaodNeeded = true; lblError.Text = ex.Message; lblError.Visible = true; } this.lblInfo.Visible = true; this.lblInfo.Text = GetString("general.changessaved"); if (relaodNeeded) { // Get the active cultures from DB DataSet ds = CultureInfoProvider.GetCultures("CultureID IN (SELECT CultureID FROM CMS_SiteCulture WHERE SiteID = " + si.SiteID + ")", null, 0, "CultureCode"); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SqlHelperClass.GetStringValues(ds.Tables[0], "CultureCode")); uniSelector.Value = currentValues; uniSelector.Reload(true); } } }
public void Validate_ThereAreAsyncRules_ThrowsException() { // ARRANGE var validation = new ValidationHelper(); // Add a simple sync rule validation.AddRule(RuleResult.Valid); // Add an async rule validation.AddAsyncRule(onCompleted => onCompleted(RuleResult.Invalid("Error"))); // ACT Assert.Throws<InvalidOperationException>(() => { validation.ValidateAll(); }); }
public void ValidationCompleted_ValidateRuleWithMultipleTargets_ResultContainsErrorsForAllTargsts() { // Arrange var validation = new ValidationHelper(); var dummy = new DummyViewModel(); validation.AddRule(() => dummy.Foo, () => dummy.Bar, () => { return RuleResult.Invalid("Error"); }); // Act var result = validation.ValidateAll(); // Assert Assert.False(result.IsValid); Assert.True(result.ErrorList.Count == 2, "There must be two errors: one for each property target"); Assert.True(Equals(result.ErrorList[0].Target, "dummy.Foo"), "Target for the first error must be dummy.Foo"); Assert.True(Equals(result.ErrorList[1].Target, "dummy.Bar"), "Target for the second error must be dummy.Bar"); }
public void DropDownAddsUnobtrusiveValidationAttributes() { // Arrange const string fieldName = "name"; var modelStateDictionary = new ModelStateDictionary(); var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary); HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper); // Act validationHelper.RequireField(fieldName, "Please specify a valid Name."); validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: "Name cannot exceed {0} characters")); var html = helper.DropDownList(fieldName, GetSelectList(), htmlAttributes: new Dictionary<string, object> { { "data-some-val", "5" } }); // Assert Assert.Equal( "<select data-some-val=\"5\" data-val=\"true\" data-val-length=\"Name cannot exceed 30 characters\" data-val-length-max=\"30\" data-val-required=\"Please specify a valid Name.\" id=\"name\" name=\"name\">" + Environment.NewLine + "<option value=\"A\">Alpha</option>" + Environment.NewLine + "<option value=\"B\">Bravo</option>" + Environment.NewLine + "<option value=\"C\">Charlie</option>" + Environment.NewLine + "</select>", html.ToString()); }
/// <summary> /// Initializes the control properties. /// </summary> private void SetupControl() { if (StopProcessing) { // Do nothing } else { // WAI validation lblUserName = (LocalizedLabel)loginElem.FindControl("lblUserName"); if (lblUserName != null) { lblUserName.Text = GetString("general.username"); if (!ShowUserNameLabel) { lblUserName.Attributes.Add("style", "display: none;"); } } lblPassword = (LocalizedLabel)loginElem.FindControl("lblPassword"); if (lblPassword != null) { lblPassword.Text = GetString("general.password"); if (!ShowPasswordLabel) { lblPassword.Attributes.Add("style", "display: none;"); } } // Set properties for validator rfv = (RequiredFieldValidator)loginElem.FindControl("rfvUserNameRequired"); rfv.ToolTip = GetString("LogonForm.NameRequired"); rfv.Text = rfv.ErrorMessage = GetString("LogonForm.EnterName"); rfv.ValidationGroup = ClientID + "_MiniLogon"; // Set visibility of buttons login = (LocalizedButton)loginElem.FindControl("btnLogon"); if (login != null) { login.Visible = !ShowImageButton; login.ValidationGroup = ClientID + "_MiniLogon"; } loginImg = (ImageButton)loginElem.FindControl("btnImageLogon"); if (loginImg != null) { loginImg.Visible = ShowImageButton; loginImg.ImageUrl = ImageUrl; loginImg.ValidationGroup = ClientID + "_MiniLogon"; } // Ensure display control as inline and is used right default button container = (Panel)loginElem.FindControl("pnlLogonMiniForm"); if (container != null) { container.Attributes.Add("style", "display: inline;"); if (ShowImageButton) { if (loginImg != null) { container.DefaultButton = loginImg.ID; } else if (login != null) { container.DefaultButton = login.ID; } } } CMSTextBox txtUserName = (CMSTextBox)loginElem.FindControl("UserName"); if (txtUserName != null) { txtUserName.EnableAutoComplete = SecurityHelper.IsAutoCompleteEnabledForLogin(SiteContext.CurrentSiteName); } if (!string.IsNullOrEmpty(UserNameText)) { // Initialize javascript for focus and blur UserName textbox user = (TextBox)loginElem.FindControl("UserName"); user.Attributes.Add("onfocus", "MLUserFocus_" + ClientID + "('focus');"); user.Attributes.Add("onblur", "MLUserFocus_" + ClientID + "('blur');"); string focusScript = "function MLUserFocus_" + ClientID + "(type)" + "{" + "var userNameBox = document.getElementById('" + user.ClientID + "');" + "if(userNameBox.value == '" + UserNameText + "' && type == 'focus')" + "{userNameBox.value = '';}" + "else if (userNameBox.value == '' && type == 'blur')" + "{userNameBox.value = '" + UserNameText + "';}" + "}"; ScriptHelper.RegisterClientScriptBlock(this, GetType(), "MLUserNameFocus_" + ClientID, ScriptHelper.GetScript(focusScript)); } loginElem.LoggedIn += loginElem_LoggedIn; loginElem.LoggingIn += loginElem_LoggingIn; loginElem.LoginError += loginElem_LoginError; loginElem.Authenticate += loginElem_Authenticate; if (!RequestHelper.IsPostBack()) { // Set SkinID properties if (!StandAlone && (PageCycle < PageCycleEnum.Initialized) && (ValidationHelper.GetString(Page.StyleSheetTheme, "") == "")) { SetSkinID(SkinID); } } if (string.IsNullOrEmpty(loginElem.UserName)) { loginElem.UserName = UserNameText; } // Register script to update logon error message LocalizedLabel failureLit = loginElem.FindControl("FailureText") as LocalizedLabel; if (failureLit != null) { StringBuilder sbScript = new StringBuilder(); sbScript.Append(@" function UpdateLabel_", ClientID, @"(content, context) { var lbl = document.getElementById(context); if(lbl) { lbl.innerHTML = content; lbl.className = ""InfoLabel""; } }"); ScriptHelper.RegisterClientScriptBlock(this, GetType(), "InvalidLogonAttempts_" + ClientID, sbScript.ToString(), true); } } }
/// <summary> /// Load data of editing exchangeTable. /// </summary> /// <param name="exchangeTableObj">ExchangeTable object</param> protected void LoadData(ExchangeTableInfo exchangeTableObj) { editGrid.Columns[0].HeaderText = GetString("ExchangeTable_Edit.ToCurrency"); editGrid.Columns[1].HeaderText = GetString("ExchangeTable_Edit.RateValue"); // Get exchange rates and fill the dictionary DataSet dsExRates = ExchangeRateInfoProvider.GetExchangeRates(mExchangeTableId); if (!DataHelper.DataSourceIsEmpty(dsExRates)) { foreach (DataRow dr in dsExRates.Tables[0].Rows) { int toCurrencyId = ValidationHelper.GetInteger(dr["ExchangeRateToCurrencyID"], -1); if (!mExchangeRates.ContainsKey(toCurrencyId)) { mExchangeRates.Add(toCurrencyId, dr); } } } DataSet dsAllCurrencies = CurrencyInfoProvider.GetCurrencies(ConfiguredSiteID); // Row index of main currency int mainCurrIndex = -1; int i = 0; if (!DataHelper.DataSourceIsEmpty(dsAllCurrencies)) { // Find main currency in all currencies dataset if (mMainCurrency != null) { // Prepare site main currency unit label string siteCode = mMainCurrency.CurrencyCode; lblSiteMainCurrency.Text = siteCode; lblMainToSite.Text = string.Format(GetString("ExchangeTable_Edit.FromMainToSite"), HTMLHelper.HTMLEncode(siteCode)); // Prepare global main currency unit label string globalCode = CurrencyInfoProvider.GetMainCurrencyCode(0); lblFromGlobalToMain.Text = string.Format(GetString("ExchangeTable_Edit.FromGlobalToMain"), HTMLHelper.HTMLEncode(globalCode)); foreach (DataRow dr in dsAllCurrencies.Tables[0].Rows) { if (ValidationHelper.GetInteger(dr["CurrencyID"], -1) == mMainCurrency.CurrencyID) { mainCurrIndex = i; } i++; } } // Remove found main currency if (mainCurrIndex != -1) { dsAllCurrencies.Tables[0].Rows[mainCurrIndex].Delete(); dsAllCurrencies.AcceptChanges(); } } if (DataHelper.DataSourceIsEmpty(dsAllCurrencies)) { // Site exchange rates section is visible only when more currencies exist plcSiteRates.Visible = true; //false; lblMainToSite.Visible = true; //false; plcNoCurrency.Visible = true; } // Hide rates part when no grid visible plcGrid.Visible = plcSiteRates.Visible || plcRateFromGlobal.Visible; // Use currencies in grid editGrid.DataSource = dsAllCurrencies; editGrid.DataBind(); // Fill editing form if (!RequestHelper.IsPostBack()) { dtPickerExchangeTableValidFrom.SelectedDateTime = exchangeTableObj.ExchangeTableValidFrom; txtExchangeTableDisplayName.Text = exchangeTableObj.ExchangeTableDisplayName; dtPickerExchangeTableValidTo.SelectedDateTime = exchangeTableObj.ExchangeTableValidTo; txtGlobalExchangeRate.Text = Convert.ToString(exchangeTableObj.ExchangeTableRateFromGlobalCurrency); } }
public void ResultChanged_ValidateExecutedForSeveralRules_FiresForEachTarget() { // Arrange var validation = new ValidationHelper(); var dummy = new DummyViewModel(); validation.AddRule(() => dummy.Foo, () => RuleResult.Invalid("Error")); validation.AddRule(() => dummy.Foo, RuleResult.Valid); validation.AddRule(() => dummy.Bar, RuleResult.Valid); validation.AddRule(() => RuleResult.Invalid("Error")); const int expectedTimesToFire = 0 + 1 /*Invalid Foo*/+ 1 /* Invalid general target */; var eventFiredTimes = 0; validation.ResultChanged += (o, e) => { eventFiredTimes++; }; // Act validation.ValidateAll(); // Verify Assert.Equal(expectedTimesToFire, eventFiredTimes); }
/// <summary> /// Logged in handler. /// </summary> private void loginElem_LoggedIn(object sender, EventArgs e) { // Set view mode to live site after login to prevent bar with "Close preview mode" PortalContext.ViewMode = ViewModeEnum.LiveSite; // Ensure response cookie CookieHelper.EnsureResponseCookie(FormsAuthentication.FormsCookieName); // Set cookie expiration if (loginElem.RememberMeSet) { CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddYears(1), false); } else { // Extend the expiration of the authentication cookie if required if (!AuthenticationHelper.UseSessionCookies && (HttpContext.Current != null) && (HttpContext.Current.Session != null)) { CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddMinutes(Session.Timeout), false); } } // Current username string userName = loginElem.UserName; // Get user name (test site prefix too) UserInfo ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, SiteContext.CurrentSite); // Check whether safe user name is required and if so get safe username if (RequestHelper.IsMixedAuthentication() && UserInfoProvider.UseSafeUserName) { // User stored with safe name userName = ValidationHelper.GetSafeUserName(loginElem.UserName, SiteContext.CurrentSiteName); // Find user by safe name ui = UserInfoProvider.GetUserInfoForSitePrefix(userName, SiteContext.CurrentSite); if (ui != null) { // Authenticate user by site or global safe username AuthenticationHelper.AuthenticateUser(ui.UserName, loginElem.RememberMeSet); } } // Log activity (warning: CMSContext contains info of previous user) if (ui != null) { // If user name is site prefixed, authenticate user manually if (UserInfoProvider.IsSitePrefixedUser(ui.UserName)) { AuthenticationHelper.AuthenticateUser(ui.UserName, loginElem.RememberMeSet); } // Log activity MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument); } // Redirect user to the return URL, or if is not defined redirect to the default target URL var redirectUrl = RequestContext.CurrentURL; string url = QueryHelper.GetString("ReturnURL", String.Empty); if (!String.IsNullOrEmpty(url) && URLHelper.IsLocalUrl(url)) { redirectUrl = url; } else if (!String.IsNullOrEmpty(DefaultTargetUrl)) { redirectUrl = ResolveUrl(DefaultTargetUrl); } URLHelper.Redirect(redirectUrl); }
public void Validate_MultipleRulesForSameTarget_DoesNotExecuteRulesIfPerviousFailed() { // ARRANGE var validation = new ValidationHelper(); var dummy = new DummyViewModel(); bool firstRuleExecuted = false; bool secondRuleExecuted = false; validation.AddRule(() => dummy.Foo, () => { firstRuleExecuted = true; return RuleResult.Invalid("Error1"); }); validation.AddRule(() => dummy.Foo, () => { secondRuleExecuted = true; return RuleResult.Invalid("Error2"); }); // ACT validation.ValidateAll(); // VERIFY Assert.True(firstRuleExecuted, "First rule must have been executed"); Assert.False(secondRuleExecuted, "Second rule should not have been executed because first rule failed."); }
public override MessageCollection Verify() { try { var retval = new MessageCollection(); retval.AddRange(base.Verify()); var root = (ModelRoot)this.Object; //Check valid name if (!ValidationHelper.ValidDatabaseIdenitifer(root.CompanyName) || !ValidationHelper.ValidCodeIdentifier(root.CompanyName)) { retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextInvalidCompany, this); } if (!ValidationHelper.ValidDatabaseIdenitifer(root.ProjectName) || !ValidationHelper.ValidCodeIdentifier(root.ProjectName)) { retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextInvalidProject, this); } if (!ValidationHelper.ValidDatabaseIdenitifer(root.CompanyAbbreviation) || !ValidationHelper.ValidCodeIdentifier(root.CompanyAbbreviation)) { retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextInvalidCompanyAbbreviation, this); } if (!string.IsNullOrEmpty(root.DefaultNamespace)) { if (!ValidationHelper.IsValidNamespace(root.DefaultNamespace)) { retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextInvalidNamespace, this); } } return(retval); } catch (Exception ex) { throw; } }
public void Validate_ValidationResultIsValid_ToStringReturnsEmptyString() { // ARRANGE var validation = new ValidationHelper(); validation.AddRule(RuleResult.Valid); // ACT var r = validation.ValidateAll(); // VERIFY Assert.True(r.ToString() == string.Empty); }
/// <summary> /// Bind the data. /// </summary> public void Bind() { if (!string.IsNullOrEmpty(ObjectType)) { pnlGrid.Visible = true; // Initialize strings btnAllTasks.Text = GetString("ImportExport.All"); btnNoneTasks.Text = GetString("export.none"); lblTasks.Text = GetString("Export.Tasks"); // Get object info GeneralizedInfo info = ModuleManager.GetReadOnlyObject(ObjectType); if (info != null) { gvTasks.RowDataBound += gvTasks_RowDataBound; plcGrid.Visible = true; codeNameColumnName = info.CodeNameColumn; displayNameColumnName = info.DisplayNameColumn; // Task fields TemplateField taskCheckBoxField = (TemplateField)gvTasks.Columns[0]; taskCheckBoxField.HeaderText = GetString("General.Export"); TemplateField titleField = (TemplateField)gvTasks.Columns[1]; titleField.HeaderText = GetString("Export.TaskTitle"); BoundField typeField = (BoundField)gvTasks.Columns[2]; typeField.HeaderText = GetString("general.type"); BoundField timeField = (BoundField)gvTasks.Columns[3]; timeField.HeaderText = GetString("Export.TaskTime"); // Load tasks int siteId = (SiteObject ? Settings.SiteId : 0); DataSet ds = ExportTaskInfoProvider.SelectTaskList(siteId, ObjectType, null, "TaskTime DESC", 0, null, CurrentOffset, CurrentPageSize, ref pagerForceNumberOfResults); // Set correct ID for direct page contol pagerElem.DirectPageControlID = ((float)pagerForceNumberOfResults / pagerElem.CurrentPageSize > 20.0f) ? "txtPage" : "drpPage"; // Call page binding event if (OnPageBinding != null) { OnPageBinding(this, null); } if (!DataHelper.DataSourceIsEmpty(ds) && (ValidationHelper.GetBoolean(Settings.GetSettings(ImportExportHelper.SETTINGS_TASKS), true))) { plcTasks.Visible = true; gvTasks.DataSource = ds; gvTasks.DataBind(); } else { plcTasks.Visible = false; } } else { plcGrid.Visible = false; } } else { pnlGrid.Visible = false; } }
public void ValidationResultChanged_ValidateExecutedForOneRule_FiresOneTime() { // Arrange var validation = new ValidationHelper(); var dummy = new DummyViewModel(); validation.AddRule(() => dummy.Foo, () => RuleResult.Invalid("Error")); var eventFiredTimes = 0; validation.ResultChanged += (o, e) => { eventFiredTimes++; }; // Act validation.ValidateAll(); // Verity Assert.Equal(1, eventFiredTimes); }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void ugRecycleBin_OnAction(string actionName, object actionArgument) { int versionHistoryId = ValidationHelper.GetInteger(actionArgument, 0); actionName = actionName.ToLower(); switch (actionName) { case "restorechilds": case "restorewithoutbindings": case "restorecurrentsite": try { if (CMSContext.CurrentUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects")) { switch (actionName) { case "restorechilds": ObjectVersionManager.RestoreObject(versionHistoryId, true); break; case "restorewithoutbindings": ObjectVersionManager.RestoreObject(versionHistoryId, 0); break; case "restorecurrentsite": ObjectVersionManager.RestoreObject(versionHistoryId, CMSContext.CurrentSiteID); break; } lblInfo.Visible = true; lblInfo.Text = GetString("ObjectVersioning.Recyclebin.RestorationOK"); } else { lblError.Visible = true; lblError.Text = ResHelper.GetString("objectversioning.recyclebin.restorationfailedpermissions"); } } catch (CodeNameNotUniqueException ex) { lblError.Visible = true; lblError.Text = String.Format(GetString("objectversioning.restorenotuniquecodename"), (ex.Object != null) ? "('" + ex.Object.ObjectCodeName + "')" : null); } catch (Exception ex) { lblError.Visible = true; lblError.Text = GetString("objectversioning.recyclebin.restorationfailed") + GetString("general.seeeventlog"); // Log to event log LogException("OBJECTRESTORE", ex); } break; case "destroy": ObjectVersionHistoryInfo verInfo = ObjectVersionHistoryInfoProvider.GetVersionHistoryInfo(versionHistoryId); // Get object site name string siteName = null; if (CurrentSite != null) { siteName = CurrentSite.SiteName; } else { siteName = SiteInfoProvider.GetSiteName(verInfo.VersionObjectSiteID); } if ((verInfo != null) && CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, verInfo.VersionObjectType, siteName)) { ObjectVersionManager.DestroyObjectHistory(verInfo.VersionObjectType, verInfo.VersionObjectID); lblInfo.Visible = true; lblInfo.Text = GetString("ObjectVersioning.Recyclebin.DestroyOK"); } else { lblError.Visible = true; lblError.Text = String.Format(ResHelper.GetString("objectversioning.recyclebin.destructionfailedpermissions"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(verInfo.VersionObjectDisplayName))); } break; } ugRecycleBin.ResetSelection(); pnlUpdateInfo.Update(); ReloadFilter((CurrentSite != null) ? CurrentSite.SiteID : -1, IsSingleSite, false); }
public void ValidationHelper_GetValidations_AssemblyNotFound_Test() { // Assemble var valHelper = new ValidationHelper(); // Act var vals = valHelper.GetValidations("TestDTO.ValidationTest", "model", null, false, "Blah.Validation.Test"); // Assert Assert.IsNull(vals); }
protected void Page_Load(object sender, EventArgs e) { // Register the main CMS script ScriptHelper.RegisterCMS(Page); if (StopProcessing) { return; } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Set current UI culture currentCulture = CultureHelper.PreferredUICulture; if (!RequestHelper.IsCallback()) { ControlsHelper.RegisterPostbackControl(btnOk); // Create action script StringBuilder actionScript = new StringBuilder(); actionScript.Append( @" function PerformAction(selectionFunction, selectionField, dropId, validationLabel, whatId) { var selectionFieldElem = document.getElementById(selectionField); var label = document.getElementById(validationLabel); var items = selectionFieldElem.value; var whatDrp = document.getElementById(whatId); var allDocs = whatDrp.value == '", (int)What.AllObjects, @"'; var action = document.getElementById(dropId).value; if (action == '", (int)Action.SelectAction, @"') { label.innerHTML = '", GetString("massaction.selectsomeaction"), @"'; return false; } if(!eval(selectionFunction) || allDocs) { var confirmed = false; var confMessage = ''; switch(action) { case '", (int)Action.RestoreToCurrentSite, @"': case '", (int)Action.RestoreWithoutSiteBindings, @"': case '", (int)Action.Restore, @"': confMessage = '", GetString("objectversioning.recyclebin.confirmrestores"), @"'; break; case '", (int)Action.Delete, @"': confMessage = allDocs ? '", GetString("objectversioning.recyclebin.confirmemptyrecbin"), @"' : '", GetString("objectversioning.recyclebin.confirmdeleteselected") + @"'; break; } return confirm(confMessage); } else { label.innerHTML = '", GetString("objectversioning.recyclebin.selectobjects"), @"'; return false; } } function ContextBinAction_", ugRecycleBin.ClientID, @"(action, versionId) { document.getElementById('", hdnValue.ClientID, @"').value = action + ';' + versionId;", ControlsHelper.GetPostBackEventReference(btnHidden, null), @"; }"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "recycleBinScript", ScriptHelper.GetScript(actionScript.ToString())); // Set page size int itemsPerPage = ValidationHelper.GetInteger(ItemsPerPage, 0); if ((itemsPerPage > 0) && !RequestHelper.IsPostBack()) { ugRecycleBin.Pager.DefaultPageSize = itemsPerPage; } // Add action to button btnOk.OnClientClick = "return PerformAction('" + ugRecycleBin.GetCheckSelectionScript() + "','" + ugRecycleBin.GetSelectionFieldClientID() + "','" + drpAction.ClientID + "','" + lblValidation.ClientID + "', '" + drpWhat.ClientID + "');"; // Initialize dropdown lists if (!RequestHelper.IsPostBack()) { drpAction.Items.Add(new ListItem(GetString("general." + Action.Restore), Convert.ToInt32(Action.Restore).ToString())); drpAction.Items.Add(new ListItem(GetString("objectversioning.recyclebin." + Action.RestoreWithoutSiteBindings), Convert.ToInt32(Action.RestoreWithoutSiteBindings).ToString())); // Display restore to current site only if current site available CurrentSiteInfo si = CMSContext.CurrentSite; if (si != null) { drpAction.Items.Add(new ListItem(String.Format(GetString("objectversioning.recyclebin." + Action.RestoreToCurrentSite), si.DisplayName), Convert.ToInt32(Action.RestoreToCurrentSite).ToString())); } drpAction.Items.Add(new ListItem(GetString("general." + Action.Delete), Convert.ToInt32(Action.Delete).ToString())); drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.SelectedObjects), Convert.ToInt32(What.SelectedObjects).ToString())); drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.AllObjects), Convert.ToInt32(What.AllObjects).ToString())); ugRecycleBin.OrderBy = OrderBy; } string where = (IsSingleSite || (SiteName == "##global##")) ? "VersionObjectSiteID IS NULL" : null; if (CurrentSite != null) { where = SqlHelperClass.AddWhereCondition(where, "VersionObjectSiteID = " + CurrentSite.SiteID, "OR"); } ugRecycleBin.WhereCondition = GetWhereCondition(where); ugRecycleBin.HideControlForZeroRows = false; ugRecycleBin.OnExternalDataBound += ugRecycleBin_OnExternalDataBound; ugRecycleBin.OnAction += ugRecycleBin_OnAction; // Register the dialog script ScriptHelper.RegisterDialogScript(Page); // Initialize buttons btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); string error = QueryHelper.GetString("displayerror", String.Empty); if (error != String.Empty) { lblError.Text = GetString("objectversioning.recyclebin.errorsomenotdestroyed"); } // Set visibility of panels pnlLog.Visible = false; } else { ugRecycleBin.StopProcessing = true; } // Initialize filter ReloadFilter((CurrentSite != null) ? CurrentSite.SiteID : -1, IsSingleSite, false); // If filter is set if (filterBin.FilterIsSet) { ugRecycleBin.ZeroRowsText = GetString("unigrid.filteredzerorowstext"); } else { ugRecycleBin.ZeroRowsText = IsSingleSite ? GetString("objectversioning.RecycleBin.NoObjects") : GetString("RecycleBin.Empty"); } // Initialize events ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; }
public void ValidationHelper_GetValidations_Empty_Test() { // Assemble var valHelper = new ValidationHelper(); // Act var vals = valHelper.GetValidations("TestDTO.NoValidations", "model", null, false, "Intertech.Validation.Test"); // Assert Assert.IsNotNull(vals); AssertJsonEqual(_emptyValidations, vals); }
/// <summary> /// Restores objects selected in UniGrid. /// </summary> private void Restore(object parameter, Action action) { try { // Begin log AddLog(ResHelper.GetString("objectversioning.recyclebin.restoringobjects", currentCulture)); BinSettingsContainer settings = (BinSettingsContainer)parameter; DataSet recycleBin = null; if (settings.User.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects")) { string where = IsSingleSite ? "VersionObjectSiteID IS NULL" : null; switch (settings.CurrentWhat) { case What.AllObjects: if (settings.Site != null) { where = SqlHelperClass.AddWhereCondition(where, "VersionObjectSiteID = " + settings.Site.SiteID, "OR"); } recycleBin = ObjectVersionHistoryInfoProvider.GetRecycleBin(GetWhereCondition(where), null, -1, "VersionID, VersionObjectDisplayName, VersionObjectType, VersionObjectID"); break; case What.SelectedObjects: ArrayList toRestore = ugRecycleBin.SelectedItems; // Restore selected objects if (toRestore.Count > 0) { where = SqlHelperClass.GetWhereCondition("VersionID", (string[])toRestore.ToArray(typeof(string))); recycleBin = ObjectVersionHistoryInfoProvider.GetRecycleBin(where, OrderBy, -1, "VersionID, VersionObjectDisplayName, VersionObjectType, VersionObjectID"); } break; } if (!DataHelper.DataSourceIsEmpty(recycleBin)) { RestoreDataSet(settings, recycleBin, action); } } else { CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailedpermissions"); AddLog(CurrentError); } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled CurrentInfo = ResHelper.GetString("Recyclebin.RestorationCanceled", currentCulture); AddLog(CurrentInfo); } else { // Log error CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailed", currentCulture) + ": " + ResHelper.GetString("general.seeeventlog", currentCulture); AddLog(CurrentError); // Log to event log LogException("OBJECTRESTORE", ex); } } catch (Exception ex) { // Log error CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailed", currentCulture) + ": " + ResHelper.GetString("general.seeeventlog", currentCulture); AddLog(CurrentError); // Log to event log LogException("OBJECTRESTORE", ex); } }
public void ValidationHelper_Constructor_Test() { // Assemble // Act var valHelper = new ValidationHelper(); // Assert var converters = valHelper.Converters; Assert.IsNotNull(converters); Assert.IsTrue(converters.Count == 10); }
/// <summary> /// Restores set of given version histories. /// </summary> /// <param name="currentUserInfo">Current user info</param> /// <param name="recycleBin">DataSet with nodes to restore</param> private void RestoreDataSet(BinSettingsContainer settings, DataSet recycleBin, Action action) { // Result flags bool resultOK = true; if (!DataHelper.DataSourceIsEmpty(recycleBin)) { // Restore all objects foreach (DataRow dataRow in recycleBin.Tables[0].Rows) { int versionId = ValidationHelper.GetInteger(dataRow["VersionID"], 0); // Log current event string taskTitle = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(dataRow["VersionObjectDisplayName"], string.Empty))); // Restore object if (versionId > 0) { GeneralizedInfo restoredObj = null; try { switch (action) { case Action.Restore: restoredObj = ObjectVersionManager.RestoreObject(versionId, true); break; case Action.RestoreToCurrentSite: restoredObj = ObjectVersionManager.RestoreObject(versionId, CMSContext.CurrentSiteID); break; case Action.RestoreWithoutSiteBindings: restoredObj = ObjectVersionManager.RestoreObject(versionId, 0); break; } } catch (CodeNameNotUniqueException ex) { CurrentError = String.Format(GetString("objectversioning.restorenotuniquecodename"), (ex.Object != null) ? "('" + ex.Object.ObjectCodeName + "')" : null); AddLog(CurrentError); } if (restoredObj != null) { AddLog(ResHelper.GetString("general.object", currentCulture) + " '" + taskTitle + "'"); } else { // Set result flag if (resultOK) { resultOK = false; } } } } } if (resultOK) { CurrentInfo = ResHelper.GetString("ObjectVersioning.Recyclebin.RestorationOK", currentCulture); AddLog(CurrentInfo); } else { CurrentError = ResHelper.GetString("objectversioning.recyclebin.restorationfailed", currentCulture); AddLog(CurrentError); } }
public void ListBoxAddsUnobtrusiveValidationAttributes() { // Arrange const string fieldName = "name"; var modelStateDictionary = new ModelStateDictionary(); var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary); HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper); // Act validationHelper.RequireField(fieldName, "Please specify a valid Name."); validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: "Name cannot exceed {0} characters")); var html = helper.ListBox(fieldName, GetSelectList(), htmlAttributes: new Dictionary<string, object> { { "data-some-val", "5" } }); // Assert Assert.Equal(@"<select data-some-val=""5"" data-val=""true"" data-val-length=""Name cannot exceed 30 characters"" data-val-length-max=""30"" data-val-required=""Please specify a valid Name."" id=""name"" name=""name""> <option value=""A"">Alpha</option> <option value=""B"">Bravo</option> <option value=""C"">Charlie</option> </select>", html.ToString()); }
/// <summary> /// Empties recycle bin. /// </summary> private void EmptyBin(object parameter) { // Begin log AddLog(ResHelper.GetString("Recyclebin.EmptyingBin", currentCulture)); BinSettingsContainer settings = (BinSettingsContainer)parameter; CurrentUserInfo currentUserInfo = settings.User; SiteInfo currentSite = settings.Site; DataSet recycleBin = null; string where = IsSingleSite ? "VersionObjectSiteID IS NULL" : null; switch (settings.CurrentWhat) { case What.AllObjects: if (currentSite != null) { where = SqlHelperClass.AddWhereCondition(where, "VersionObjectSiteID = " + currentSite.SiteID, "OR"); } where = GetWhereCondition(where); break; case What.SelectedObjects: ArrayList toRestore = ugRecycleBin.SelectedItems; // Restore selected objects if (toRestore.Count > 0) { where = SqlHelperClass.GetWhereCondition("VersionID", (string[])toRestore.ToArray(typeof(string))); } break; } recycleBin = ObjectVersionHistoryInfoProvider.GetRecycleBin(where, null, -1, "VersionID, VersionObjectType, VersionObjectID, VersionObjectDisplayName, VersionObjectSiteID"); try { if (!DataHelper.DataSourceIsEmpty(recycleBin)) { foreach (DataRow dr in recycleBin.Tables[0].Rows) { int versionHistoryId = Convert.ToInt32(dr["VersionID"]); string versionObjType = Convert.ToString(dr["VersionObjectType"]); string objName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(dr["VersionObjectDisplayName"], string.Empty))); string siteName = null; if (currentSite != null) { siteName = currentSite.SiteName; } else { int siteId = ValidationHelper.GetInteger(dr["VersionObjectSiteID"], 0); siteName = SiteInfoProvider.GetSiteName(siteId); } // Check permissions if (!currentUserInfo.IsAuthorizedPerObject(PermissionsEnum.Destroy, versionObjType, siteName)) { CurrentError = String.Format(ResHelper.GetString("objectversioning.Recyclebin.DestructionFailedPermissions", currentCulture), objName); AddLog(CurrentError); } else { AddLog(ResHelper.GetString("general.object", currentCulture) + " '" + objName + "'"); // Destroy the version int versionObjId = ValidationHelper.GetInteger(dr["VersionObjectID"], 0); ObjectVersionManager.DestroyObjectHistory(versionObjType, versionObjId); LogContext.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Objects", "DESTROYOBJECT", currentUserInfo.UserID, currentUserInfo.UserName, 0, null, HTTPHelper.UserHostAddress, ResHelper.GetString("objectversioning.Recyclebin.objectdestroyed"), (currentSite != null) ? currentSite.SiteID : 0, HTTPHelper.GetAbsoluteUri(), HTTPHelper.MachineName, HTTPHelper.GetUrlReferrer(), HTTPHelper.GetUserAgent()); } } if (!String.IsNullOrEmpty(CurrentError)) { CurrentError = ResHelper.GetString("objectversioning.recyclebin.errorsomenotdestroyed", currentCulture); AddLog(CurrentError); } else { CurrentInfo = ResHelper.GetString("ObjectVersioning.Recyclebin.DestroyOK", currentCulture); AddLog(CurrentInfo); } } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state != CMSThread.ABORT_REASON_STOP) { // Log error CurrentError = "Error occurred: " + ResHelper.GetString("general.seeeventlog", currentCulture); AddLog(CurrentError); // Log to event log LogException("EMPTYINGBIN", ex); } } catch (Exception ex) { // Log error CurrentError = "Error occurred: " + ResHelper.GetString("general.seeeventlog", currentCulture); AddLog(CurrentError); // Log to event log LogException("EMPTYINGBIN", ex); } }
public ValidatableViewModel() { Validator = new ValidationHelper(); DataErrorInfoValidationAdapter = new NotifyDataErrorInfoAdapter(Validator); }
protected void btnOk_OnClick(object sender, EventArgs e) { pnlLog.Visible = true; CurrentError = string.Empty; CurrentLog.Close(); EnsureLog(); int actionValue = ValidationHelper.GetInteger(drpAction.SelectedValue, 0); Action action = (Action)actionValue; int whatValue = ValidationHelper.GetInteger(drpWhat.SelectedValue, 0); currentWhat = (What)whatValue; ctlAsync.Parameter = new BinSettingsContainer(CurrentUser, currentWhat, CurrentSite); switch (action) { case Action.Restore: case Action.RestoreToCurrentSite: case Action.RestoreWithoutSiteBindings: switch (currentWhat) { case What.AllObjects: titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_RecycleBin/restoreall.png"); break; case What.SelectedObjects: titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_RecycleBin/restoreselected.png"); if (ugRecycleBin.SelectedItems.Count <= 0) { return; } break; } titleElemAsync.TitleText = GetString("objectversioning.Recyclebin.Restoringobjects"); switch (action) { case Action.Restore: RunAsync(RestoreWithChilds); break; case Action.RestoreToCurrentSite: RunAsync(RestoreToCurrentSite); break; case Action.RestoreWithoutSiteBindings: RunAsync(RestoreWithoutSiteBindings); break; } break; case Action.Delete: switch (currentWhat) { case What.AllObjects: titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_RecycleBin/emptybin.png"); break; case What.SelectedObjects: titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_RecycleBin/emptyselected.png"); break; } titleElemAsync.TitleText = GetString("recyclebin.emptyingbin"); RunAsync(EmptyBin); break; } }
public void CheckboxAddsUnobtrusiveValidationAttributes() { // Arrange const string fieldName = "name"; var modelStateDictionary = new ModelStateDictionary(); var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary); HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper); // Act validationHelper.RequireField(fieldName, "Please specify a valid Name."); validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: "Name cannot exceed {0} characters")); var html = helper.CheckBox(fieldName, new Dictionary<string, object> { { "data-some-val", "5" } }); // Assert Assert.Equal(@"<input data-some-val=""5"" data-val=""true"" data-val-length=""Name cannot exceed 30 characters"" data-val-length-max=""30"" data-val-required=""Please specify a valid Name."" id=""name"" name=""name"" type=""checkbox"" />", html.ToString()); }
protected object ugRecycleBin_OnExternalDataBound(object sender, string sourceName, object parameter) { sourceName = sourceName.ToLower(); DataRowView data = null; string objType = null; switch (sourceName) { case "view": ImageButton imgView = ((ImageButton)sender); if (imgView != null) { GridViewRow gvr = (GridViewRow)parameter; data = (DataRowView)gvr.DataItem; string viewVersionUrl = ResolveUrl("~/CMSModules/Objects/Dialogs/ViewObjectVersion.aspx?showall=1&nocompare=1&versionhistoryid=" + ValidationHelper.GetInteger(data["VersionID"], 0)); viewVersionUrl = URLHelper.AddParameterToUrl(viewVersionUrl, "hash", QueryHelper.GetHash(viewVersionUrl)); imgView.OnClientClick = "window.open(" + ScriptHelper.GetString(viewVersionUrl) + ");return false;"; } break; case "destroy": ImageButton imgDestroy = sender as ImageButton; if (imgDestroy != null) { DataRowView dr = (DataRowView)(((GridViewRow)parameter).DataItem); objType = ValidationHelper.GetString(dr["VersionObjectType"], null); // Get object site name string siteName = null; if (CurrentSite != null) { siteName = CurrentSite.SiteName; } else { int siteId = ValidationHelper.GetInteger(dr["VersionObjectSiteID"], 0); siteName = SiteInfoProvider.GetSiteName(siteId); } } break; case "restorechilds": ImageButton imgRestore = sender as ImageButton; if (imgRestore != null) { imgRestore.ImageUrl = GetImageUrl("CMSModules/CMS_RecycleBin/restorechilds.png"); } break; case "deletedwhen": case "deletedwhentooltip": DateTime deletedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); bool displayGMT = (sourceName == "deletedwhentooltip"); return(TimeZoneHelper.ConvertToUserTimeZone(deletedWhen, displayGMT, CurrentUser, CurrentSite)); case "versionobjecttype": objType = ValidationHelper.GetString(parameter, ""); return(HTMLHelper.HTMLEncode(GetString("ObjectType." + objType.Replace(".", "_")))); } return(HTMLHelper.HTMLEncode(parameter.ToString())); }
private void SetupValidation() { var validationRules = new ValidationHelper(); // Simple properties validationRules.AddRule(() => StringProperty, () => { return RuleResult.Assert(!string.IsNullOrEmpty(StringProperty), "StringProperty cannot be null or empty string"); }); validationRules.AddRule(() => IntProperty, () => { return RuleResult.Assert(IntProperty > 0, "IntProperty should be greater than zero."); }); // Dependant properties validationRules.AddRule(() => RangeStart, () => RangeEnd, () => { return RuleResult.Assert(RangeEnd > RangeStart, "RangeEnd must be grater than RangeStart"); }); // Long-running validation (simulates call to a web service or something) validationRules.AddRule( () => StringProperty2, () => { if (SyncValidationRuleExecutedAsyncroniouslyDelegate != null) { SyncValidationRuleExecutedAsyncroniouslyDelegate(); } return RuleResult.Assert(!string.IsNullOrEmpty(StringProperty2), "StringProperty2 cannot be null or empty string"); }); Validation = validationRules; DataErrorInfoValidationAdapter = new NotifyDataErrorInfoAdapter(Validation); }
/// <summary> /// Returns URL of the media item according site settings. /// </summary> /// <param name="fileInfo">File info object</param> /// <param name="site">Information on site file belongs to</param> /// <param name="fileGuid">GUID of the file URL is generated for</param> /// <param name="fileName">Name of the file URL is generated for</param> /// <param name="fileExtension">Extension of the file URL is generated for</param> /// <param name="filePath">Media file path of the file URL is generated for</param> /// <param name="isPreview">Indicates whether the file URL is generated for preview</param> /// <param name="height">Specifies height of the image</param> /// <param name="width">Specifies width of the image</param> /// <param name="maxSideSize">Maximum dimension for images displayed for thumbnails view</param> public string GetItemUrl(MediaFileInfo fileInfo, SiteInfo site, Guid fileGuid, string fileName, string fileExtension, string filePath, bool isPreview, int height, int width, int maxSideSize) { string result; bool resize = (maxSideSize > 0); fileName = UsePermanentUrls ? AttachmentHelper.GetFullFileName(fileName, fileExtension) : fileName; bool generateFullURL = ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CMSUseMediaFileAbsoluteURLs"], false); if ((Config != null) && (Config.UseFullURL || generateFullURL || (SiteContext.CurrentSiteID != LibraryInfo.LibrarySiteID) || (SiteContext.CurrentSiteID != GetCurrentSiteId()))) { // If permanent URLs should be generated if (UsePermanentUrls || resize || isPreview) { // URL in format 'http://domainame/getmedia/123456-25245-45454-45455-5455555545/testfile.gif' result = MediaFileURLProvider.GetMediaFileAbsoluteUrl(site.SiteName, fileGuid, fileName); } else { // URL in format 'http://domainame/cms/EcommerceSite/media/testlibrary/folder1/testfile.gif' result = MediaFileURLProvider.GetMediaFileAbsoluteUrl(site.SiteName, LibraryInfo.LibraryFolder, filePath); } } else { if (UsePermanentUrls || resize || isPreview) { // URL in format '/cms/getmedia/123456-25245-45454-45455-5455555545/testfile.gif' result = MediaFileURLProvider.GetMediaFileUrl(fileGuid, fileName); } else { if (fileInfo != null) { result = MediaFileURLProvider.GetMediaFileUrl(fileInfo, SiteContext.CurrentSiteName, LibraryInfo.LibraryFolder); } else { // URL in format '/cms/EcommerceSite/media/testlibrary/folder1/testfile.gif' result = MediaFileURLProvider.GetMediaFileUrl(SiteContext.CurrentSiteName, LibraryInfo.LibraryFolder, filePath); } } } // If image dimensions are specified if (resize) { result = URLHelper.AddParameterToUrl(result, "maxsidesize", maxSideSize.ToString()); } if (height > 0) { result = URLHelper.AddParameterToUrl(result, "height", height.ToString()); } if (width > 0) { result = URLHelper.AddParameterToUrl(result, "width", width.ToString()); } // Media selctor should returns non-resolved URL in all cases bool isMediaSelector = (OutputFormat == OutputFormatEnum.URL) && (SelectableContent == SelectableContentEnum.OnlyMedia); return(isMediaSelector ? result : URLHelper.ResolveUrl(result)); }