/// <summary> /// Compares inner string value with checked value and sets the check box accordingly. /// </summary> private void HandleStringValue() { var innerValueString = ValidationHelper.GetString(mInnerValue, null); checkbox.Checked = CMSString.Equals(CheckedValue.ToString(), innerValueString); }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); #region "Watermark extender" // Watermark extender // Disable watermark extender for nonempty fields (issue with value which is same as the watermark text) string resolvedWatermarkText = ContextResolver.ResolveMacros(WatermarkText); if (!String.IsNullOrEmpty(WatermarkText) && !String.IsNullOrEmpty(resolvedWatermarkText) && !CMSString.Equals(textbox.Text, WatermarkText)) { // Create extender TextBoxWatermarkExtender exWatermark = new TextBoxWatermarkExtender(); exWatermark.ID = "exWatermark"; exWatermark.TargetControlID = textbox.ID; exWatermark.EnableViewState = false; Controls.Add(exWatermark); // Initialize extender exWatermark.WatermarkText = resolvedWatermarkText; exWatermark.WatermarkCssClass = textbox.CssClass + " " + ValidationHelper.GetString(GetValue("WatermarkCssClass"), WatermarkCssClass); } #endregion #region "Filter extender" if (FilterEnabled) { // Create extender FilteredTextBoxExtender exFilter = new FilteredTextBoxExtender(); exFilter.ID = "exFilter"; exFilter.TargetControlID = textbox.ID; exFilter.EnableViewState = false; Controls.Add(exFilter); // Filter extender exFilter.FilterInterval = FilterInterval; // Set the filter type if (FilterTypeValue == null) { exFilter.FilterType = FilterType; } else { if (!string.IsNullOrEmpty(FilterTypeValue)) { FilterTypes filterType = 0; string[] types = FilterTypeValue.Split(new char[] { ';', '|' }, StringSplitOptions.RemoveEmptyEntries); if (types.Length > 0) { foreach (string typeStr in types) { int type = ValidationHelper.GetInteger(typeStr, 0); switch (type) { case FILTER_NUMBERS: filterType |= FilterTypes.Numbers; break; case FILTER_LOWERCASE: filterType |= FilterTypes.LowercaseLetters; break; case FILTER_UPPERCASE: filterType |= FilterTypes.UppercaseLetters; break; case FILTER_CUSTOM: filterType |= FilterTypes.Custom; break; } } exFilter.FilterType = filterType; } } } FilterModes filterMode = FilterMode; // Set valid and invalid characters if (exFilter.FilterType == FilterTypes.Custom) { // When filter type is Custom only, filter mode can be anything exFilter.FilterMode = filterMode; if (filterMode == FilterModes.InvalidChars) { exFilter.InvalidChars = InvalidChars; } else { exFilter.ValidChars = ValidChars; } } else { // Otherwise filter type must be valid chars exFilter.FilterMode = FilterModes.ValidChars; // Set valid chars only if original filter mode was valid chars and filter type contains Custom if ((filterMode == FilterModes.ValidChars) && ((exFilter.FilterType & FilterTypes.Custom) != 0)) { exFilter.ValidChars = ValidChars; } } } #endregion #region "Autocomplete extender" // Autocomplete extender if (!string.IsNullOrEmpty(AutoCompleteServiceMethod) && !string.IsNullOrEmpty(AutoCompleteServicePath)) { // Create extender AutoCompleteExtender exAuto = new AutoCompleteExtender(); exAuto.ID = "exAuto"; exAuto.TargetControlID = textbox.ID; exAuto.EnableViewState = false; Controls.Add(exAuto); exAuto.ServiceMethod = AutoCompleteServiceMethod; exAuto.ServicePath = URLHelper.ResolveUrl(AutoCompleteServicePath); exAuto.MinimumPrefixLength = AutoCompleteMinimumPrefixLength; exAuto.ContextKey = ContextResolver.ResolveMacros(AutoCompleteContextKey); exAuto.CompletionInterval = AutoCompleteCompletionInterval; exAuto.EnableCaching = AutoCompleteEnableCaching; exAuto.CompletionSetCount = AutoCompleteCompletionSetCount; exAuto.CompletionListCssClass = AutoCompleteCompletionListCssClass; exAuto.CompletionListItemCssClass = AutoCompleteCompletionListItemCssClass; exAuto.CompletionListHighlightedItemCssClass = AutoCompleteCompletionListHighlightedItemCssClass; exAuto.DelimiterCharacters = AutoCompleteDelimiterCharacters; exAuto.FirstRowSelected = AutoCompleteFirstRowSelected; exAuto.ShowOnlyCurrentWordInCompletionListItem = AutoCompleteShowOnlyCurrentWordInCompletionListItem; } #endregion }
protected void btnOK_Click(object sender, EventArgs e) { // History back count BackCount++; string result = null; // Trim the key before save string key = txtKey.Text.Trim(); // Validate the code name if default culture if (uic.UICultureCode == CultureHelper.DefaultUICulture) { result = new Validator() .NotEmpty(key, rfvKey.ErrorMessage) .IsCodeName(key, GetString("Administration-UICulture_String_New.InvalidCodeName")) .Result; } if (!string.IsNullOrEmpty(result)) { // Display error message ShowError(result); return; } // Update the string ResourceStringInfo ri = SqlResourceManager.GetResourceStringInfo(stringID, uiCultureID); if (ri != null) { // Check if string with given key is not already defined ResourceStringInfo existing = SqlResourceManager.GetResourceStringInfo(key); if ((existing == null) || (existing.StringId == ri.StringId)) { ri.StringIsCustom = chkCustomString.Checked; ri.UICultureCode = uic.UICultureCode; ri.TranslationText = txtText.Text; if (txtKey.Visible) { // If key changed, log deletion of old string string newKey = key; if ((!CMSString.Equals(ri.StringKey, newKey, true)) && (ri.Generalized.LogSynchronization == SynchronizationTypeEnum.LogSynchronization)) { SynchronizationHelper.LogObjectChange(ri, TaskTypeEnum.DeleteObject); } ri.StringKey = key; } // Update key SqlResourceManager.SetResourceStringInfo(ri); ShowChangesSaved(); tabs[1, 0] = ri.StringKey; } else { ShowError(string.Format(GetString("Administration-UICulture_String_New.StringExists"), key)); } } }
/// <summary> /// Binds grid with properties. /// </summary> private void BindProperties() { // Clear rows grdUserProperties.Rows.Clear(); // Create list of AD properties List <ComboBoxItemContainer> attributeList = new List <ComboBoxItemContainer>(); switch (ImportProfile.BindingEditorMode) { case BindingEditorMode.Simple: foreach (string attr in ADSimpleUserProperties) { string attrName = ResHelper.GetString("ADAttribute_" + attr); if (attr != ADProvider.NoneAttribute) { attrName += " (" + attr + ")"; } ComboBoxItemContainer container = new ComboBoxItemContainer(attrName, attr); attributeList.Add(container); } break; case BindingEditorMode.Advanced: // Add 'none' item attributeList.Add(new ComboBoxItemContainer(ResHelper.GetString("ADAttribute_" + ADProvider.NoneAttribute), ADProvider.NoneAttribute)); // Add non-culture-specific attributes attributeList.AddRange(ADProvider.GetUserAttributes().Select(attribute => new ComboBoxItemContainer(attribute, attribute))); break; } // Sort attributes alphabetically attributeList.Sort((c1, c2) => CMSString.Compare(c1.DisplayMember, c2.DisplayMember, StringComparison.OrdinalIgnoreCase)); if (CMSUserProperties.Count == 0) { // Load user data class DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(UserInfo.OBJECT_TYPE); // Load columns from the user data class LoadColumns(dci); // Load user settings data class dci = DataClassInfoProvider.GetDataClassInfo(UserSettingsInfo.OBJECT_TYPE); // Load columns from the user settings data class LoadColumns(dci); // Sort properties by name CMSUserProperties.Sort(); } // Create default preselection if (ImportProfile.UserProperties.Count == 0) { ImportProfile.UserProperties.Add("FirstName", "givenName"); ImportProfile.UserProperties.Add("MiddleName", "middleName"); ImportProfile.UserProperties.Add("LastName", "sn"); ImportProfile.UserProperties.Add("Email", "mail"); } foreach (string property in CMSUserProperties) { // Create new row DataGridViewRow dr = new DataGridViewRow(); // Create cell with CMS property DataGridViewTextBoxCell cmsProp = new DataGridViewTextBoxCell(); cmsProp.Value = property; // Create cell with AD attributes DataGridViewComboBoxCell adAttr = new DataGridViewComboBoxCell(); // Bind combobox cell adAttr.DisplayMember = "DisplayMember"; adAttr.ValueMember = "ValueMember"; adAttr.DataSource = attributeList; // Preselect values based on import profile if (ImportProfile.UserProperties.ContainsKey(property)) { string val = ImportProfile.UserProperties[property]; if (!chkAllAttributes.Checked && !ADSimpleUserProperties.Contains(val)) { // Add values selected in advanced mode attributeList.Add(new ComboBoxItemContainer(val, val)); } adAttr.Value = val; } else { // Set empty mapping adAttr.Value = ADProvider.NoneAttribute; } // Add both cells to datarow dr.Cells.Add(cmsProp); dr.Cells.Add(adAttr); // Set CMS property read-only cmsProp.ReadOnly = true; // Add row to DataGridView grdUserProperties.Rows.Add(dr); } }
/// <summary> /// Saves resource translations and returns TRUE if save was successful. Returns FALSE if any error occurred. /// </summary> private bool Save() { bool saved = true; // Check permissions if (CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Localization", "LocalizeStrings")) { // Change resource key string key = txtStringKey.Text.Trim(); if (key != rsi.StringKey) { // Validate the key string result = new Validator().NotEmpty(key, rfvKey.ErrorMessage).IsCodeName(key, GetString("Administration-UICulture_String_New.InvalidCodeName")).Result; if (String.IsNullOrEmpty(result)) { ResourceStringInfo riNew = SqlResourceManager.GetResourceStringInfo(txtStringKey.Text.Trim()); // Check if string with given key is not already defined if ((riNew == null) || (rsi.StringId == riNew.StringId)) { // Log deletion of old string if ((!CMSString.Equals(key, rsi.StringKey, true)) && (rsi.Generalized.LogSynchronization == SynchronizationTypeEnum.LogSynchronization)) { SynchronizationHelper.LogObjectChange(rsi, TaskTypeEnum.DeleteObject); } rsi.StringKey = key; SqlResourceManager.SetResourceStringInfo(rsi); } // New resource key collides with already existing resource key else { ShowError(String.Format(GetString("Administration-UICulture_String_New.StringExists"), key)); saved = false; } } // New resource string key is not code name else { ShowError(result); saved = false; } } string existingTranslation = null; string newTranslation = null; FormEngineUserControl control = null; // Go through all cultures foreach (string cultureCode in translations.Keys) { // Check if translation in given culture exists existingTranslation = SqlResourceManager.GetStringStrictly(txtStringKey.Text, cultureCode); // Get control for given culture control = (FormEngineUserControl)translations[cultureCode]; if (control != null) { // Translation is not already created if (String.IsNullOrEmpty(existingTranslation)) { // Get new translation newTranslation = ValidationHelper.GetString(control.Value, String.Empty).Trim(); // Create new translation in given culture if (!String.IsNullOrEmpty(newTranslation)) { UpdateString(cultureCode, newTranslation); } // Translation of default culture must exist else if (cultureCode == CultureHelper.DefaultUICulture) { ShowError(String.Format(ResHelper.GetString("localizable.deletedefault"), defaultCultureName)); saved = false; } } // Existing translation is being updated else { newTranslation = ValidationHelper.GetString(control.Value, String.Empty).Trim(); // Delete translation if new translation is empty if (String.IsNullOrEmpty(newTranslation)) { // Delete translation if (cultureCode != CultureHelper.DefaultUICulture) { SqlResourceManager.DeleteResourceStringInfo(txtStringKey.Text, cultureCode); } // Translation in default culture cannot be deleted or set to empty in Localizable textbox else { ShowError(String.Format(ResHelper.GetString("localizable.deletedefault"), defaultCultureName)); saved = false; } } // Update translation if new translation is not empty else { UpdateString(cultureCode, newTranslation); } } // Set updated translation in current culture if (cultureCode == CultureHelper.PreferredUICulture) { defaultTranslation = newTranslation; } } } } // Current user is not global admin else { ShowError(GetString("general.actiondenied")); saved = false; pnlControls.Visible = false; } return(saved); }
protected void Page_Load(object sender, EventArgs e) { if (!RequestHelper.IsPostBack()) { string preferredCultureCode = LocalizationContext.PreferredCultureCode; string currentSiteName = SiteContext.CurrentSiteName; var documentCultures = Node.GetTranslatedCultures(); // Get site cultures DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName); if (!DataHelper.DataSourceIsEmpty(siteCultures) && (documentCultures.Count > 0)) { string suffixNotTranslated = GetString("SplitMode.NotTranslated"); foreach (DataRow row in siteCultures.Tables[0].Rows) { string cultureCode = ValidationHelper.GetString(row["CultureCode"], null); string cultureName = ResHelper.LocalizeString(ValidationHelper.GetString(row["CultureName"], null)); string suffix = string.Empty; // Compare with preferred culture if (CMSString.Compare(preferredCultureCode, cultureCode, true) == 0) { suffix = GetString("SplitMode.Current"); } else if (!documentCultures.Contains(cultureCode)) { suffix = suffixNotTranslated; } // Add new item var item = new ListItem(cultureName + " " + suffix, cultureCode); drpCultures.Items.Add(item); } } drpCultures.SelectedValue = PortalUIHelper.SplitModeCultureCode; drpCultures.Attributes.Add("onchange", "if (parent.CheckChanges('frame2')) { parent.FSP_ChangeCulture(this); }"); } buttons.Actions.Add(new CMSButtonGroupAction { Name = "close", UseIconButton = true, OnClientClick = "FSP_Close();return false;", IconCssClass = "icon-l-list-titles", ToolTip = GetString("splitmode.closelayout") }); buttons.Actions.Add(new CMSButtonGroupAction { Name = "vertical", UseIconButton = true, OnClientClick = "FSP_Layout('true','frame1','Vertical');return false;", IconCssClass = "icon-l-cols-2 js-split-vertical", ToolTip = GetString("splitmode.verticallayout") }); buttons.Actions.Add(new CMSButtonGroupAction { Name = "horizontal", UseIconButton = true, OnClientClick = "FSP_Layout(false,'frame1Vertical','Horizontal');;return false;", IconCssClass = "icon-l-rows-2 js-split-horizontal", ToolTip = GetString("splitmode.horizontallayout") }); // Set css class switch (PortalUIHelper.SplitMode) { case SplitModeEnum.Horizontal: buttons.SelectedActionName = "horizontal"; break; case SplitModeEnum.Vertical: buttons.SelectedActionName = "vertical"; break; default: buttons.SelectedActionName = "close"; break; } // Synchronize image chckScroll.Checked = PortalUIHelper.SplitModeSyncScrollbars; StringBuilder script = new StringBuilder(); script.Append( @" function FSP_Layout(vertical, frameName, cssClassName) { if ((frameName != null) && parent.CheckChanges(frameName)) { if (cssClassName != null) { var element = document.getElementById('", pnlMain.ClientID, @"'); if (element != null) { element.setAttribute(""class"", 'SplitToolbar ' + cssClassName); element.setAttribute(""className"", 'SplitToolbar ' + cssClassName); } } var divRight = document.getElementById('", divRight.ClientID, @"'); if (vertical) { divRight.setAttribute(""class"", 'RightAlign'); parent.FSP_VerticalLayout(); } else { divRight.setAttribute(""class"", ''); parent.FSP_HorizontalLayout(); } } } function FSP_Close() { if (parent.CheckChanges()) { parent.FSP_CloseSplitMode(); } } "); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "toolbarScript_" + ClientID, ScriptHelper.GetScript(script.ToString())); chckScroll.Attributes.Add("onchange", "javascript:parent.FSP_SynchronizeToolbar()"); // Set layout if (PortalUIHelper.SplitMode == SplitModeEnum.Horizontal) { pnlMain.CssClass = "SplitToolbar Horizontal"; divRight.Attributes["class"] = null; } else if (PortalUIHelper.SplitMode == SplitModeEnum.Vertical) { pnlMain.CssClass = "SplitToolbar Vertical"; } // Register Init script - FSP_ToolbarInit(selectorId, checkboxId) StringBuilder initScript = new StringBuilder(); initScript.Append("parent.FSP_ToolbarInit('", drpCultures.ClientID, "','", chckScroll.ClientID, "');"); // Register js scripts ScriptHelper.RegisterJQuery(Page); ScriptHelper.RegisterStartupScript(Page, typeof(string), "FSP_initToolbar", ScriptHelper.GetScript(initScript.ToString())); }
/// <summary> /// Saves the given DataRow data to the web part properties. /// </summary> /// <param name="form">Form to save</param> /// <param name="pti">Page template instance</param> /// <param name="isLayoutWidget">Indicates whether the edited widget is a layout widget</param> private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti, bool isLayoutWidget) { if (form.Visible && (mWidgetInstance != null)) { // Keep the old ID to check the change of the ID string oldId = mWidgetInstance.ControlID.ToLowerCSafe(); DataRow dr = form.DataRow; foreach (DataColumn column in dr.Table.Columns) { mWidgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()]; mWidgetInstance.SetValue(column.ColumnName, dr[column]); // If name changed, move the content // (This can happen when a user overrides the WidgetControlID property to be visible in the widget properties dialog) if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0) { try { string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe(); // Name changed if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0)) { WidgetIdChanged = true; WidgetId = newId; // Move the document content if present string currentContent = CurrentPageInfo.EditableWebParts[oldId]; if (currentContent != null) { TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); // Move the content in the page info CurrentPageInfo.EditableWebParts[oldId] = null; CurrentPageInfo.EditableWebParts[newId] = currentContent; // Update the document node.SetValue("DocumentContent", CurrentPageInfo.GetContentXml()); DocumentHelper.UpdateDocument(node, mTreeProvider); } // Change the underlying zone names if layout widget if (isLayoutWidget) { string prefix = oldId + "_"; foreach (WebPartZoneInstance zone in pti.WebPartZones) { if (zone.ZoneID.StartsWithCSafe(prefix, true)) { // Change the zone prefix to the new one zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length)); } } } } } catch (Exception ex) { EventLogProvider.LogException("Content", "CHANGEWIDGET", ex); } } } } }
protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterJQuery(Page); ScriptHelper.RegisterScriptFile(Page, "~/CMSAdminControls/UI/UniMenu/UniMenu.js"); currentSiteName = (SiteID != 0) ? SiteInfoProvider.GetSiteName(SiteID) : CMSContext.CurrentSiteName; DataSet siteCulturesDS = CultureInfoProvider.GetSiteCultures(currentSiteName); if (!DataHelper.DataSourceIsEmpty(siteCulturesDS)) { // Register jQuery cookie script ScriptHelper.RegisterJQueryCookie(Page); string defaultCulture = CultureHelper.GetDefaultCulture(currentSiteName); DataTable siteCultures = siteCulturesDS.Tables[0]; culturesCount = siteCultures.Rows.Count; if ((culturesCount <= MaxCulturesInRow) && (culturesCount > 1)) { // Disable cultures menu btnCultures.StopProcessing = true; for (int i = 0; i < culturesCount; i++) { string cultureCode = siteCultures.Rows[i]["CultureCode"].ToString(); string cultureShortName = siteCultures.Rows[i]["CultureShortName"].ToString(); string cultureLongName = ResHelper.LocalizeString(siteCultures.Rows[i]["CultureName"].ToString()); if (CMSString.Compare(cultureCode, defaultCulture, true) == 0) { cultureLongName += " " + GetString("general.defaultchoice"); } MenuItem item = new MenuItem(); item.Text = HTMLHelper.HTMLEncode(cultureShortName); item.Tooltip = cultureLongName; item.CssClass = "BigButton"; item.OnClientClick = "ChangeLanguage('" + cultureCode + "')"; item.ImagePath = GetFlagIconUrl(cultureCode, "48x48"); item.ImageAltText = cultureLongName; item.ImageAlign = ImageAlign.Top; item.MinimalWidth = 48; buttons.Buttons.Add(item); if (SelectedCulture.ToLowerCSafe() == cultureCode.ToLowerCSafe()) { buttons.SelectedIndex = i; } } } else { // Do not show culture selection buttons buttons.StopProcessing = true; CultureInfo ci = CultureInfoProvider.GetCultureInfo(SelectedCulture); MenuItem item = new MenuItem(); item.Text = ci.CultureShortName; item.Tooltip = GetString(ci.CultureName); item.ImagePath = GetFlagIconUrl(SelectedCulture, UseSmallLanguageButton ? "16x16" : "48x48"); item.ImageAltText = GetString(ci.CultureName); SetStyles(item); // Generate submenu only if more cultures to choose from if (culturesCount > 1) { foreach (DataRow row in siteCultures.Rows) { string cultureCode = row["CultureCode"].ToString(); string cultureShortName = row["CultureShortName"].ToString(); string cultureLongName = GetString(row["CultureName"].ToString()); if (CMSString.Compare(cultureCode, defaultCulture, true) == 0) { cultureLongName += " " + GetString("general.defaultchoice"); } string flagUrl = GetFlagIconUrl(cultureCode, "16x16"); string flagBigUrl = GetFlagIconUrl(cultureCode, "48x48"); SubMenuItem menuItem = new SubMenuItem() { Text = cultureLongName, Tooltip = cultureLongName, ImagePath = flagUrl, ImageAltText = cultureShortName, OnClientClick = String.Format("CMSUniMenu.ChangeButton(##BUTTON##, {0}, {1}); ChangeLanguage({2});", ScriptHelper.GetString(cultureShortName), ScriptHelper.GetString(ResolveUrl(flagBigUrl)), ScriptHelper.GetString(cultureCode)) }; item.SubItems.Add(menuItem); } } btnCultures.Buttons.Add(item); } if (culturesCount > 1) { string compare = GetString("SplitMode.Compare"); // Split mode button MenuItem splitItem = new MenuItem(); splitItem.Text = compare; splitItem.Tooltip = GetString("SplitMode.CompareLangVersions"); splitItem.OnClientClick = "ChangeSplitMode()"; splitItem.ImagePath = GetImageUrl("CMSModules/CMS_Content/Menu/Compare.png"); splitItem.ImageAltText = compare; splitItem.AllowToggle = true; splitItem.IsToggled = CMSContext.DisplaySplitMode; SetStyles(splitItem); splitView.Buttons.Add(splitItem); } else { splitView.StopProcessing = true; } } }
/// <summary> /// Handles btnOK's OnClick event - Update resource info. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // finds whether required fields are not empty string result = new Validator() .NotEmpty(txtCultureName.Text.Trim(), rfvCultureName.ErrorMessage) .NotEmpty(txtCultureCode.Text.Trim(), rfvCultureCode.ErrorMessage) .Result; if (txtCultureCode.Text.Trim().Length > 10) { result = GetString("Culture.MaxLengthError"); } try { // Chech if global culture exists if (new System.Globalization.CultureInfo(txtCultureCode.Text.Trim()) == null) { result = GetString("Culture.ErrorNoGlobalCulture"); } } catch { result = GetString("Culture.ErrorNoGlobalCulture"); } txtCultureAlias.Text = URLHelper.GetSafeUrlPart(txtCultureAlias.Text.Trim(), String.Empty); string cultureAlias = txtCultureAlias.Text.Trim().Replace("'", "''"); // Check whether culture alias is unique if (!string.IsNullOrEmpty(cultureAlias)) { string where = string.Format("(CultureCode = N'{0} 'OR CultureAlias = N'{0}') AND CultureID <> {1}", cultureAlias, culture.CultureID); DataSet cultures = CultureInfoProvider.GetCultures(where, null, 1, "CultureID"); if ((!DataHelper.DataSourceIsEmpty(cultures)) || (CMSString.Equals(cultureAlias, txtCultureCode.Text.Trim(), true))) { result = GetString("Culture.AliasNotUnique"); } } if (result != string.Empty) { ShowError(result); return; } // finds if the culture code is unique CultureInfo uniqueCulture = CultureInfoProvider.GetCultureInfoForCulture(txtCultureCode.Text.Trim()); // if culture code already exists and it is just editing culture -> update if ((uniqueCulture == null) || (uniqueCulture.CultureID == culture.CultureID)) { UpdateCulture(); } // if culture code already exists and it is another culture -> error else { ShowError(GetString("Culture_New.CultureExists")); } }
/// <summary> /// Handles OnAfterValidate event of the UI form. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">Event argument</param> protected void OnAfterValidate(object sender, EventArgs e) { int cultureId = Control.EditedObject.Generalized.ObjectID; string cultureCode = ValidationHelper.GetString(Control.GetFieldValue("CultureCode"), String.Empty).Trim(); string cultureAlias = ValidationHelper.GetString(Control.GetFieldValue("CultureAlias"), String.Empty).Trim(); // Check validity of culture code if (!CultureHelper.IsValidCultureInfoName(cultureCode)) { Control.ShowError(Control.GetString("Culture.ErrorNoGlobalCulture")); Control.StopProcessing = true; } // Neutral culture cannot be used if (CultureHelper.IsNeutralCulture(cultureCode) && !Control.StopProcessing) { Control.ShowError(Control.GetString("culture.neutralculturecannotbeused")); Control.StopProcessing = true; } // Check if culture already exists for new created cultures var cultureByCode = CultureInfoProvider.GetCultureInfoForCulture(cultureCode); if ((cultureByCode != null) && (cultureByCode.CultureID != cultureId) && !Control.StopProcessing) { Control.ShowError(Control.GetString("culture_new.cultureexists")); Control.StopProcessing = true; } // Check whether culture alias is unique if (!String.IsNullOrEmpty(cultureAlias) && !Control.StopProcessing) { CultureInfo cultureByAlias = CultureInfoProvider.GetCultureInfoForCulture(cultureAlias); if (((cultureByAlias != null) && (cultureByAlias.CultureID != cultureId)) || CMSString.Equals(cultureAlias, cultureCode, true)) { Control.ShowError(Control.GetString("Culture.AliasNotUnique")); Control.StopProcessing = true; } } // Show warning if culture is UI and there is no resx file bool isUiCulture = ValidationHelper.GetBoolean(Control.GetFieldValue("CultureIsUICulture"), false); if (!Control.StopProcessing && !LocalizationHelper.ResourceFileExistsForCulture(cultureCode) && isUiCulture) { string url = "http://devnet.kentico.com/download/localization-packs"; string downloadPage = String.Format(@"<a href=""{0}"" target=""_blank"" >{1}</a> ", url, HTMLHelper.HTMLEncode(url)); Control.ShowWarning(String.Format(Control.GetString("culture.downloadlocalization"), downloadPage)); } }
/// <summary> /// Handles the ButtonOK's onClick event. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // finds whether required fields are not empty or well filled string result = new Validator().NotEmpty(tbDisplayName.Text.Trim(), GetString("DocumentType_Edit_General.DisplayNameRequired")). NotEmpty(tbNamespaceName.Text.Trim(), GetString("DocumentType_Edit_General.NamespaceNameRequired")). NotEmpty(tbCodeName.Text.Trim(), GetString("DocumentType_Edit_General.CodeNameRequired")). IsIdentifier(tbNamespaceName.Text.Trim(), GetString("DocumentType_Edit_General.NamespaceNameIdentifier")). IsCodeName(tbCodeName.Text.Trim(), GetString("DocumentType_Edit_General.CodeNameIdentifier")).Result; // Get full class name string newClassName = tbNamespaceName.Text.Trim() + "." + tbCodeName.Text.Trim(); DataClassInfo classInfo = DataClassInfoProvider.GetDataClass(documentTypeId); // Check if class exists if (classInfo == null) { return; } className = classInfo.ClassName; bool classNameChanged = (CMSString.Compare(className, newClassName, true) != 0); // Check if new class name is unique if (classNameChanged) { DataClassInfo ci = DataClassInfoProvider.GetDataClass(newClassName); if ((ci != null) && (ci.ClassID != classInfo.ClassID)) { result += String.Format(GetString("class.exists"), newClassName); } } if (result == "") { classInfo = classInfo.Clone(); int originalInherits = classInfo.ClassInheritsFromClassID; int inherits = ValidationHelper.GetInteger(selInherits.Value, 0); classInfo.ClassInheritsFromClassID = inherits; // sets properties of the classInfo classInfo.ClassDisplayName = tbDisplayName.Text.Trim(); classInfo.ClassName = newClassName; classInfo.ClassNewPageURL = txtNewPage.Text.Trim(); classInfo.ClassEditingPageURL = tbEditingPage.Text.Trim(); classInfo.ClassListPageURL = tbListPage.Text.Trim(); classInfo.ClassViewPageUrl = txtViewPage.Text.Trim(); classInfo.ClassPreviewPageUrl = txtPreviewPage.Text.Trim(); classInfo.ClassUsePublishFromTo = chkClassUsePublishFromTo.Checked; classInfo.ClassIsMenuItemType = chkIsMenuItem.Checked; // Show template selection bool templateSelection = (classInfo.ClassShowTemplateSelection = chkTemplateSelection.Checked); if (templateSelection) { classInfo.ClassPageTemplateCategoryID = categorySelector.SelectedCategoryID; } else { classInfo.ClassPageTemplateCategoryID = 0; } classInfo.ClassDefaultPageTemplateID = templateDefault.PageTemplateID; classInfo.ClassLoadGeneration = drpGeneration.Value; // Refresh the tabs according to ClassIsProduct setting ScriptHelper.RefreshTabHeader(Page, null); try { bool structureChanged = false; // Ensure (update) the inheritance if (originalInherits != inherits) { if (inherits > 0) { // Update the inherited fields DataClassInfo parentClass = DataClassInfoProvider.GetDataClass(inherits); if (parentClass != null) { FormHelper.UpdateInheritedClass(parentClass, classInfo); } } else { // Remove the inherited fields FormHelper.RemoveInheritance(classInfo, false); } structureChanged = true; } // Updates data class in DB (inner unique class name check) DataClassInfoProvider.SetDataClass(classInfo); if ((className.ToLowerCSafe() != newClassName.ToLowerCSafe()) && (classInfo.ClassIsDocumentType)) { structureChanged = true; // Class name was changed -> update queries SqlGenerator.GenerateQuery(newClassName, "searchtree", SqlOperationTypeEnum.SearchTree, false); SqlGenerator.GenerateQuery(newClassName, "selectdocuments", SqlOperationTypeEnum.SelectDocuments, false); SqlGenerator.GenerateQuery(newClassName, "selectversions", SqlOperationTypeEnum.SelectVersions, false); } if (structureChanged) { // Create view for document types SqlGenerator.GenerateDefaultView(classInfo, null); // Clear class structures ClassStructureInfo.Remove(classInfo.ClassName, true); } // Refresh document type icons bool classIsCoupled = classInfo.ClassIsCoupledClass; RefreshIcon(className, newClassName, classNameChanged, classIsCoupled, null); RefreshIcon(className, newClassName, classNameChanged, classIsCoupled, "48x48"); pnlIcons.Update(); className = newClassName; // Show message ShowChangesSaved(); } catch (Exception ex) { EventLogProvider.LogException("Document types", "UPDATE", ex); // Show error message ShowError(ex.Message); } } else { // hides asp validators in case the javascript is disabled RequiredFieldValidatorDisplayName.Visible = false; RequiredFieldValidatorNamespaceName.Visible = false; RequiredFieldValidatorCodeName.Visible = false; RegularExpressionValidatorNameSpaceName.Visible = false; RegularExpressionValidatorCodeName.Visible = false; // Show error message ShowError(result); } }
/// <summary> /// Save button action. /// </summary> protected void ObjectManager_OnSaveData(object sender, SimpleObjectManagerEventArgs e) { // Template has to exist if (PageTemplate == null) { return; } // Limit text length txtTemplateCodeName.Text = TextHelper.LimitLength(txtTemplateCodeName.Text.Trim(), 100, ""); txtTemplateDisplayName.Text = TextHelper.LimitLength(txtTemplateDisplayName.Text.Trim(), 200, ""); // Finds whether required fields are not empty string result = String.Empty; result = new Validator().NotEmpty(txtTemplateDisplayName.Text, GetString("Administration-PageTemplate_General.ErrorEmptyTemplateDisplayName")).NotEmpty(txtTemplateCodeName.Text, GetString("Administration-PageTemplate_General.ErrorEmptyTemplateCodeName")) .IsCodeName(txtTemplateCodeName.Text, GetString("general.invalidcodename")) .Result; if ((result == String.Empty) && (SelectedPageType == PageTemplateTypeEnum.Aspx || SelectedPageType == PageTemplateTypeEnum.AspxPortal)) { if (!FileSystemSelector.IsValid()) { result = FileSystemSelector.ValidationError; } } // If name changed, check if new name is unique if ((result == String.Empty) && (CMSString.Compare(PageTemplate.CodeName, txtTemplateCodeName.Text, true) != 0)) { if (PageTemplateInfoProvider.PageTemplateNameExists(txtTemplateCodeName.Text)) { result = GetString("general.codenameexists"); } } // Check dashboard prerequisites if ((PageTemplate.PageTemplateId > 0) && (SelectedPageType == PageTemplateTypeEnum.Dashboard)) { // Check live site usage TreeProvider tp = new TreeProvider(CMSContext.CurrentUser); NodeSelectionParameters parameters = new NodeSelectionParameters() { ClassNames = TreeProvider.ALL_CLASSNAMES, SiteName = TreeProvider.ALL_SITES, Columns = "NodeID", Where = String.Format("DocumentPageTemplateID = {0} OR NodeTemplateID = {0} OR NodeWireframeTemplateID = {0}", PageTemplate.PageTemplateId) }; DataSet ds = tp.SelectNodes(parameters); if (!DataHelper.DataSourceIsEmpty(ds)) { result = GetString("template.dahsboardliveused"); } // Check valid zones if (String.IsNullOrEmpty(result)) { PageTemplateInstance inst = PageTemplate.TemplateInstance; if (inst != null) { foreach (WebPartZoneInstance zone in inst.WebPartZones) { switch (zone.WidgetZoneType) { case WidgetZoneTypeEnum.Dashboard: case WidgetZoneTypeEnum.None: continue; } result = GetString("template.dashboardinvalidzone"); break; } } } } if (String.IsNullOrEmpty(result)) { // Update page template info PageTemplate.DisplayName = txtTemplateDisplayName.Text; PageTemplate.CodeName = txtTemplateCodeName.Text; PageTemplate.Description = txtTemplateDescription.Text; PageTemplate.CategoryID = Convert.ToInt32(categorySelector.Value); if (SelectedPageType == PageTemplateTypeEnum.MVC) { // MVC template PageTemplate.IsPortal = false; PageTemplate.FileName = String.Empty; PageTemplate.ShowAsMasterTemplate = false; PageTemplate.PageTemplateCloneAsAdHoc = false; PageTemplate.PageTemplateDefaultController = txtController.Text; PageTemplate.PageTemplateDefaultAction = txtAction.Text; } else if (SelectedPageType == PageTemplateTypeEnum.Portal) { // Portal template of various types PageTemplate.IsPortal = true; PageTemplate.FileName = String.Empty; // Save inherit levels if (!chkShowAsMasterTemplate.Checked) { PageTemplate.InheritPageLevels = ValidationHelper.GetString(lvlElem.Value, ""); } else { PageTemplate.InheritPageLevels = "/"; } // Show hide inherit levels radio buttons PageTemplate.ShowAsMasterTemplate = chkShowAsMasterTemplate.Checked; PageTemplate.PageTemplateCloneAsAdHoc = chkAdHoc.Checked; } else { // ASPX page templates PageTemplate.IsPortal = false; PageTemplate.FileName = FileSystemSelector.Value.ToString(); PageTemplate.ShowAsMasterTemplate = false; PageTemplate.PageTemplateCloneAsAdHoc = false; PageTemplate.InheritPageLevels = ""; } PageTemplate.PageTemplateType = SelectedPageType; // Set ad-hoc status PageTemplate.IsReusable = pageTemplateIsReusable; if (pageTemplateIsReusable) { PageTemplate.PageTemplateNodeGUID = Guid.Empty; } PageTemplate.WebParts = pageTemplateWebParts; try { // Save the template and update the header PageTemplateInfoProvider.SetPageTemplateInfo(PageTemplate); ScriptHelper.RegisterStartupScript(this, typeof(string), "pageTemplateSaveScript", ScriptHelper.GetScript("RefreshContent()")); ShowChangesSaved(); } catch (UnauthorizedAccessException ex) { ShowError(ResHelper.GetStringFormat("general.sourcecontrolerror", ex.Message)); } catch (Exception ex) { ShowError(ex.Message); } } else { rfvTemplateDisplayName.Visible = false; rfvTemplateCodeName.Visible = false; ShowError(result); } }
private void InitPreviewUrl() { bool isFile = CMSString.Equals(Node.NodeClassName, SystemDocumentTypes.File, true); lnkPreviewURL.Attributes.Add("href", Node.GetPreviewLink(CurrentUser.UserName, isFile, embededInAdministration: false)); }
protected DataSet gridDocuments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { columns = SqlHelper.MergeColumns(DocumentHelper.GETDOCUMENTS_REQUIRED_COLUMNS, "NodeAlias, NodeGUID, DocumentName, DocumentCulture, DocumentModifiedWhen, Published, DocumentType, DocumentWorkflowStepID, DocumentCheckedOutByUserID, SiteName, NodeSiteID, NodeOwner, FileAttachment, FileDescription, DocumentName AS PublishedDocumentName, DocumentType AS PublishedDocumentType"); if (CheckPermissions) { columns = SqlHelper.MergeColumns(TreeProvider.SECURITYCHECK_REQUIRED_COLUMNS, columns); } string whereCondition = null; // Filter group documents whereCondition = (GroupID != 0) ? SqlHelper.AddWhereCondition(whereCondition, "(NodeGroupID=" + GroupID + ") OR (NodeGroupID IS NULL)") : SqlHelper.AddWhereCondition(whereCondition, "NodeGroupID IS NULL"); // Retrieve documents DataSet documentsDataSet = DocumentHelper.GetDocuments(CurrentSite.SiteName, MacroResolver.ResolveCurrentPath(LibraryPath) + "/%", null, CombineWithDefaultCulture, CMS_FILE, whereCondition, currentOrder, 1, false, currentTopN, columns, TreeProvider); NodePermissionsEnum[] permissionsToCheck = null; // Filter documents by permissions if (CheckPermissions) { documentsDataSet = TreeSecurityProvider.FilterDataSetByPermissions(documentsDataSet, NodePermissionsEnum.Read, CurrentUser); permissionsToCheck = new NodePermissionsEnum[] { NodePermissionsEnum.Modify, NodePermissionsEnum.ModifyPermissions, NodePermissionsEnum.Delete }; } string cultures = PreferredCultureCode; if (CombineWithDefaultCulture) { string siteDefaultCulture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName); if (CMSString.Compare(siteDefaultCulture, PreferredCultureCode, true) != 0) { cultures += ";" + siteDefaultCulture; } } if (CheckPermissions) { // Ensure permissions flags documentsDataSet = TreeSecurityProvider.FilterDataSetByPermissions(documentsDataSet, permissionsToCheck, CurrentUser, false, cultures); } // Filter archived documents for users without modify permission if (!DataHelper.DataSourceIsEmpty(documentsDataSet)) { DataTable dt = documentsDataSet.Tables[0]; ArrayList deleteRows = new ArrayList(); foreach (DataRow dr in dt.Rows) { // If the document is not published and user hasn't modify permission, remove it from data set bool isPublished = ValidationHelper.GetBoolean(dr["Published"], true); string documentCulture = ValidationHelper.GetString(dr["DocumentCulture"], null); bool hasModify = TreeSecurityProvider.CheckPermission(dr, NodePermissionsEnum.Modify, documentCulture); if (!isPublished && !hasModify) { deleteRows.Add(dr); } } // Remove archived documents foreach (DataRow dr in deleteRows) { dt.Rows.Remove(dr); } } totalRecords = DataHelper.GetItemsCount(documentsDataSet); return(documentsDataSet); }
protected void Page_Load(object sender, EventArgs e) { if (!RequestHelper.IsPostBack()) { string preferredCultureCode = CMSContext.PreferredCultureCode; string currentSiteName = CMSContext.CurrentSiteName; string where = "CultureCode IN (SELECT DocumentCulture FROM View_CMS_Tree_Joined WHERE NodeID = " + Node.NodeID + ")"; DataSet documentCultures = CultureInfoProvider.GetCultures(where, null, 0, "CultureCode"); // Get site cultures DataSet siteCultures = CultureInfoProvider.GetSiteCultures(currentSiteName); if (!DataHelper.DataSourceIsEmpty(siteCultures) && !DataHelper.DataSourceIsEmpty(documentCultures)) { string suffixNotTranslated = GetString("SplitMode.NotTranslated"); foreach (DataRow row in siteCultures.Tables[0].Rows) { string cultureCode = ValidationHelper.GetString(row["CultureCode"], null); string cultureName = ResHelper.LocalizeString(ValidationHelper.GetString(row["CultureName"], null)); string suffix = string.Empty; // Compare with preferred culture if (CMSString.Compare(preferredCultureCode, cultureCode, true) == 0) { suffix = GetString("SplitMode.Current"); } else { // Find culture DataRow[] findRows = documentCultures.Tables[0].Select("CultureCode = '" + cultureCode + "'"); if (findRows.Length == 0) { suffix = suffixNotTranslated; } } // Add new item ListItem item = new ListItem(cultureName + " " + suffix, cultureCode); drpCultures.Items.Add(item); } } drpCultures.SelectedValue = CMSContext.SplitModeCultureCode; drpCultures.Attributes.Add("onchange", "if (parent.CheckChanges('frame2')) { parent.FSP_ChangeCulture(this); }"); } // Image URL and tooltip helpElem.IconUrl = GetImageUrl("Design/Controls/SplitView/splitviewhelpicon.png"); imgHorizontal.ImageUrl = UIHelper.GetImageUrl(Page, HorizontalImageUrl); imgVertical.ImageUrl = UIHelper.GetImageUrl(Page, VerticalImageUrl); imgClose.ImageUrl = UIHelper.GetImageUrl(Page, CloseImageUrl); imgHorizontal.ToolTip = GetString("splitmode.horizontallayout"); imgVertical.ToolTip = GetString("splitmode.verticallayout"); imgClose.ToolTip = GetString("splitmode.closesplitmode"); // Set css class switch (CMSContext.SplitMode) { case SplitModeEnum.Horizontal: divHorizontal.Attributes["class"] = buttonSelectedClass; divVertical.Attributes["class"] = buttonClass; break; case SplitModeEnum.Vertical: divHorizontal.Attributes["class"] = buttonClass; divVertical.Attributes["class"] = buttonSelectedClass; break; default: divHorizontal.Attributes["class"] = buttonClass; divVertical.Attributes["class"] = buttonClass; break; } string checkedSyncUrl = UIHelper.GetImageUrl(Page, mSyncCheckedImageUrl); string uncheckedSyncUrl = UIHelper.GetImageUrl(Page, mSyncUncheckedImageUrl); // Synchronize image string tooltip = GetString("splitmode.scrollbarsynchronization"); imgSync.AlternateText = tooltip; imgSync.ToolTip = tooltip; imgSync.ImageUrl = CMSContext.SplitModeSyncScrollbars ? checkedSyncUrl : uncheckedSyncUrl; StringBuilder script = new StringBuilder(); script.Append(@" function FSP_Layout(vertical, frameName, cssClassName) { if ((frameName != null) && parent.CheckChanges(frameName)) { if (cssClassName != null) { var element = document.getElementById('", pnlMain.ClientID, @"'); if (element != null) { element.setAttribute(""class"", 'SplitToolbar ' + cssClassName); element.setAttribute(""className"", 'SplitToolbar ' + cssClassName); } } var divRight = document.getElementById('", divRight.ClientID, @"'); if (vertical) { divRight.setAttribute(""class"", 'RightAlign'); parent.FSP_VerticalLayout(); } else { divRight.setAttribute(""class"", ''); parent.FSP_HorizontalLayout(); } } }"); script.Append(@" function FSP_Close() { if (parent.CheckChanges()) { parent.FSP_CloseSplitMode(); } }" ); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "toolbarScript_" + ClientID, ScriptHelper.GetScript(script.ToString())); // Register js events imgHorizontal.Attributes.Add("onclick", "javascript:FSP_Layout(false,'frame1Vertical','Horizontal');"); imgHorizontal.AlternateText = GetString("SplitMode.Horizontal"); imgVertical.Attributes.Add("onclick", "javascript:FSP_Layout('true','frame1','Vertical');"); imgVertical.AlternateText = GetString("SplitMode.Vertical"); imgClose.Attributes.Add("onclick", "javascript:FSP_Close();"); imgSync.Attributes.Add("onclick", "javascript:parent.FSP_SynchronizeToolbar()"); imgClose.Style.Add("cursor", "pointer"); // Set layout if (CMSContext.SplitMode == SplitModeEnum.Horizontal) { pnlMain.CssClass = "SplitToolbar Horizontal"; divRight.Attributes["class"] = null; } else if (CMSContext.SplitMode == SplitModeEnum.Vertical) { pnlMain.CssClass = "SplitToolbar Vertical"; } // Register Init script - FSP_ToolbarInit(selectorId, checkboxId) StringBuilder initScript = new StringBuilder(); initScript.Append("parent.FSP_ToolbarInit('", drpCultures.ClientID, "','", imgSync.ClientID, "','", checkedSyncUrl, "','", uncheckedSyncUrl, "','", divHorizontal.ClientID, "','", divVertical.ClientID, "');"); // Register js scripts ScriptHelper.RegisterJQuery(Page); ScriptHelper.RegisterStartupScript(Page, typeof(string), "FSP_initToolbar", ScriptHelper.GetScript(initScript.ToString())); }
protected void drpTransformationType_SelectedIndexChanged(object sender, EventArgs e) { // Get the current code string code = TransformationCode; switch (drpType.SelectedValue.ToLowerCSafe()) { case "ascx": // Convert to ASCX syntax if (CMSString.Equals(drpType.SelectedValue, "ascx", true)) { code = MacroSecurityProcessor.RemoveSecurityParameters(code, false, null); code = code.Replace("{% Register", "<%@ Register").Replace("{%", "<%#").Replace("%}", "%>"); } ShowMessage(); break; case "xslt": // No transformation break; default: // Convert to macro syntax code = code.Replace("<%@", "{%").Replace("<%#", "{%").Replace("<%=", "{%").Replace("<%", "{%").Replace("%>", "%}"); break; } // Move the content if necessary if (CMSString.Equals(drpType.SelectedValue, "html", true)) { // Move from text to WYSIWYG if (txtCode.Visible) { tbWysiwyg.ResolvedValue = code; tbWysiwyg.Visible = true; txtCode.Text = string.Empty; txtCode.Visible = false; } } else { // Move from WYSIWYG to text if (tbWysiwyg.Visible) { code = HttpUtility.HtmlDecode(code); txtCode.Text = code; txtCode.Visible = true; tbWysiwyg.ResolvedValue = string.Empty; tbWysiwyg.Visible = false; } else { txtCode.Text = code; } } SetEditor(); }
/// <summary> /// Saves the given DataRow data to the web part properties. /// </summary> /// <param name="form">Form to save</param> /// <param name="pti">Page template instance</param> private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti) { if (form.Visible && (widgetInstance != null)) { // Keep the old ID to check the change of the ID string oldId = widgetInstance.ControlID.ToLowerCSafe(); 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.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()]; widgetInstance.SetValue(column.ColumnName, dr[column]); // If name changed, move the content if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0) { try { string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe(); // Name changed if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0)) { mWidgetIdChanged = true; WidgetId = newId; // Move the document content if present string currentContent = 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.StartsWithCSafe(prefix, true)) { // 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); } } } } }
/// <summary> /// Initializes controls for activity rule. /// </summary> private void InitActivityRuleControls(string selectedActivityType) { ucActivityType.OnSelectedIndexChanged += new EventHandler(ucActivityType_OnSelectedIndexChanged); // Init activity selector from edited object if any string activityType = selectedActivityType; if ((EditForm.EditedObject != null) && !RequestHelper.IsPostBack()) { ucActivityType.Value = ValidationHelper.GetString(EditForm.Data["RuleParameter"], PredefinedActivityType.ABUSE_REPORT); activityType = ucActivityType.SelectedValue; PreviousActivityType = activityType; } // List of ignored columns string ignoredColumns = "|activitytype|activitysiteid|activityguid|activityactivecontactid|activityoriginalcontactid|pagevisitid|pagevisitactivityid|searchid|searchactivityid|"; // List of activities with "ActivityValue" StringBuilder sb = new StringBuilder(); sb.Append("|"); sb.Append(PredefinedActivityType.PURCHASE); sb.Append("|"); sb.Append(PredefinedActivityType.PURCHASEDPRODUCT); sb.Append("|"); sb.Append(PredefinedActivityType.RATING); sb.Append("|"); sb.Append(PredefinedActivityType.POLL_VOTING); sb.Append("|"); sb.Append(PredefinedActivityType.PRODUCT_ADDED_TO_SHOPPINGCART); sb.Append("|"); string showActivityValueFor = sb.ToString(); // Get columns from OM_Activity (i.e. base table for all activities) ActivityTypeInfo ati = ActivityTypeInfoProvider.GetActivityTypeInfo(activityType); FormInfo fi = new FormInfo(null); // Get columns from additional table (if any) according to selected activity type (page visit, search) FormInfo additionalFieldsForm = null; bool extraFieldsAtEnd = true; switch (activityType) { case PredefinedActivityType.PAGE_VISIT: case PredefinedActivityType.LANDING_PAGE: // Page visits additionalFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.PAGEVISIT, false); break; case PredefinedActivityType.INTERNAL_SEARCH: case PredefinedActivityType.EXTERNAL_SEARCH: // Search additionalFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.SEARCH, false); extraFieldsAtEnd = false; break; } // Get the activity form elements FormInfo filterFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.ACTIVITY, true); var elements = filterFieldsForm.GetFormElements(true, false); FormCategoryInfo newCategory = null; string caption = null; string captionKey = null; foreach (var elem in elements) { if (elem is FormCategoryInfo) { // Form category newCategory = (FormCategoryInfo)elem; } else if (elem is FormFieldInfo) { // Form field FormFieldInfo ffi = (FormFieldInfo)elem; // Skip ignored columns if (ignoredColumns.IndexOfCSafe("|" + ffi.Name.ToLowerCSafe() + "|") >= 0) { continue; } string controlName = null; if (!ffi.PrimaryKey && (fi.GetFormField(ffi.Name) == null)) { // Set default filters switch (ffi.DataType) { case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.LongText: controlName = "textfilter"; ffi.Settings["OperatorFieldName"] = ffi.Name + ".operator"; break; case FormFieldDataTypeEnum.DateTime: controlName = "datetimefilter"; ffi.Settings["SecondDateFieldName"] = ffi.Name + ".seconddatetime"; break; case FormFieldDataTypeEnum.Integer: case FormFieldDataTypeEnum.LongInteger: controlName = "numberfilter"; ffi.Settings["OperatorFieldName"] = ffi.Name + ".operator"; break; case FormFieldDataTypeEnum.GUID: continue; } // For item ID and detail ID fields use control defined in activity type if (CMSString.Compare(ffi.Name, "ActivityItemID", true) == 0) { if (ati.ActivityTypeMainFormControl == null) { continue; } if (ati.ActivityTypeMainFormControl != String.Empty) { // Check if user defined control exists FormUserControlInfo fui = FormUserControlInfoProvider.GetFormUserControlInfo(ati.ActivityTypeMainFormControl); if (fui != null) { controlName = ati.ActivityTypeMainFormControl; } } // Set detailed caption captionKey = "activityitem." + activityType; caption = GetString(captionKey); if (!caption.EqualsCSafe(captionKey, true)) { ffi.Caption = caption; } } else if (CMSString.Compare(ffi.Name, "ActivityItemDetailID", true) == 0) { if (ati.ActivityTypeDetailFormControl == null) { continue; } if (ati.ActivityTypeDetailFormControl != String.Empty) { // Check if user defined control exists FormUserControlInfo fui = FormUserControlInfoProvider.GetFormUserControlInfo(ati.ActivityTypeDetailFormControl); if (fui != null) { controlName = ati.ActivityTypeDetailFormControl; } } // Set detailed caption captionKey = "activityitemdetail." + activityType; caption = GetString(captionKey); if (!caption.EqualsCSafe(captionKey, true)) { ffi.Caption = caption; } } else if (CMSString.Compare(ffi.Name, "ActivityNodeID", true) == 0) { // Document selector for NodeID controlName = "selectdocument"; } else if (CMSString.Compare(ffi.Name, "ActivityCulture", true) == 0) { // Culture selector for culture controlName = "sitecultureselector"; } else if (CMSString.Compare(ffi.Name, "ActivityValue", true) == 0) { // Show activity value only for relevant activity types if (!ati.ActivityTypeIsCustom && (showActivityValueFor.IndexOfCSafe("|" + activityType + "|", true) < 0)) { continue; } } if (controlName != null) { // SKU selector for product ffi.Settings["controlname"] = controlName; if (CMSString.Compare(controlName, "skuselector", true) == 0) { ffi.Settings["allowempty"] = true; } } // Ensure the category if (newCategory != null) { fi.AddFormCategory(newCategory); newCategory = null; // // Extra fields at the beginning if (!extraFieldsAtEnd && (additionalFieldsForm != null)) { AddExtraFields(ignoredColumns, fi, additionalFieldsForm); additionalFieldsForm = null; } } fi.AddFormField(ffi); } } } // Extra fields at end if (extraFieldsAtEnd && (additionalFieldsForm != null)) { // Ensure the category for extra fields if (newCategory != null) { fi.AddFormCategory(newCategory); newCategory = null; } AddExtraFields(ignoredColumns, fi, additionalFieldsForm); } LoadForm(activityFormCondition, fi, activityType); }
/// <summary> /// Displays the given report /// </summary> private void DisplayReport(bool reloadInnerReport) { // If report was already displayed .. return if (mReportDisplayed) { return; } ucGraphType.ProcessChartSelectors(false); // Prepare report parameters DataTable reportParameters = new DataTable(); reportParameters.Columns.Add("FromDate", typeof(DateTime)); reportParameters.Columns.Add("ToDate", typeof(DateTime)); reportParameters.Columns.Add("CampaignName", typeof(string)); object[] parameters = new object[3]; parameters[0] = ucGraphType.From; parameters[1] = ucGraphType.To; parameters[2] = ""; // Get report name from query string reportName = ucGraphType.GetReportName(QueryHelper.GetString("reportCodeName", String.Empty)); if (CMSString.Compare(Convert.ToString(ucSelectCampaign.Value), "-1", true) != 0) { parameters[2] = ucSelectCampaign.Value; } else { reportName = "all" + reportName; } reportParameters.Rows.Add(parameters); reportParameters.AcceptChanges(); mUcDisplayReport.ReportName = reportName; // Set display report if (!mUcDisplayReport.IsReportLoaded()) { ShowError(String.Format(GetString("Analytics_Report.ReportDoesnotExist"), HTMLHelper.HTMLEncode(reportName))); } else { mUcDisplayReport.LoadFormParameters = false; mUcDisplayReport.DisplayFilter = false; mUcDisplayReport.ReportParameters = reportParameters.Rows[0]; mUcDisplayReport.GraphImageWidth = 100; mUcDisplayReport.IgnoreWasInit = true; mUcDisplayReport.UseExternalReload = true; mUcDisplayReport.UseProgressIndicator = true; if (reloadInnerReport) { mUcDisplayReport.ReloadData(true); } } if (reloadInnerReport) { // Mark as report displayed mReportDisplayed = true; } }
/// <summary> /// External history binding. /// </summary> protected object gridHistory_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView drv; switch (sourceName.ToLowerCSafe()) { case "action": drv = (DataRowView)parameter; bool wasRejected = ValidationHelper.GetBoolean(drv["WasRejected"], false); // Get type of the steps WorkflowStepTypeEnum stepType = (WorkflowStepTypeEnum)ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "StepType"), 0); WorkflowStepTypeEnum targetStepType = (WorkflowStepTypeEnum)ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "TargetStepType"), (int)stepType); WorkflowTransitionTypeEnum transitionType = (WorkflowTransitionTypeEnum)ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "HistoryTransitionType"), 0); // Get name of steps string stepName = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "StepName"), String.Empty); string targetStepName = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "TargetStepName"), stepName); if (!wasRejected) { // If step type defined, use it for identification if (targetStepType != WorkflowStepTypeEnum.Undefined) { bool isAutomatic = (transitionType == WorkflowTransitionTypeEnum.Automatic); string actionString = isAutomatic ? GetString("WorfklowProperties.Automatic") + " ({0})" : "{0}"; // Return correct step title switch (targetStepType) { case WorkflowStepTypeEnum.DocumentArchived: actionString = string.Format(actionString, GetString("WorfklowProperties.Archived")); break; case WorkflowStepTypeEnum.DocumentPublished: actionString = string.Format(actionString, GetString("WorfklowProperties.Published")); break; case WorkflowStepTypeEnum.DocumentEdit: actionString = GetString("WorfklowProperties.NewVersion"); break; default: if (stepType == WorkflowStepTypeEnum.DocumentEdit) { actionString = GetString("WorfklowProperties.NewVersion"); } else { actionString = isAutomatic ? GetString("WorfklowProperties.Automatic") : GetString("WorfklowProperties.Approved"); } break; } return(actionString); } // Backward compatibility else { // Return correct step title switch (targetStepName.ToLowerCSafe()) { case "archived": return(GetString("WorfklowProperties.Archived")); case "published": return(GetString("WorfklowProperties.Published")); case "edit": return(GetString("WorfklowProperties.NewVersion")); default: if (CMSString.Equals(stepName, "edit", true)) { return(GetString("WorfklowProperties.NewVersion")); } return(GetString("WorfklowProperties.Approved")); } } } else { return(GetString("WorfklowProperties.Rejected")); } // Get approved time case "approvedwhen": case "approvedwhentooltip": if (string.IsNullOrEmpty(parameter.ToString())) { return(string.Empty); } else { if (currentUserInfo == null) { currentUserInfo = MembershipContext.AuthenticatedUser; } if (currentSiteInfo == null) { currentSiteInfo = SiteContext.CurrentSite; } if (sourceName.EqualsCSafe("approvedwhen", StringComparison.InvariantCultureIgnoreCase)) { DateTime time = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); return(TimeZoneHelper.ConvertToUserTimeZone(time, true, currentUserInfo, currentSiteInfo)); } else { return(TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo)); } } case "stepname": drv = (DataRowView)parameter; string step = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "StepDisplayName"), String.Empty); string targetStep = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "TargetStepDisplayName"), String.Empty); if (!string.IsNullOrEmpty(targetStep)) { step += " -> " + targetStep; } return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(step))); } return(parameter); }
/// <summary> /// Sends e-mail to all attendees. /// </summary> protected void Send() { // Check 'Modify' permission if (!CheckPermissions("cms.eventmanager", "Modify")) { return; } txtSenderName.Text = txtSenderName.Text.Trim(); txtSenderEmail.Text = txtSenderEmail.Text.Trim(); txtSubject.Text = txtSubject.Text.Trim(); // Validate the fields string errorMessage = new Validator() .NotEmpty(txtSenderName.Text, GetString("Events_SendEmail.EmptySenderName")) .NotEmpty(txtSenderEmail.Text, GetString("Events_SendEmail.EmptySenderEmail")) .MatchesCondition(txtSenderEmail, input => input.IsValid(), GetString("Events_SendEmail.InvalidEmailFormat")) .NotEmpty(txtSubject.Text, GetString("Events_SendEmail.EmptyEmailSubject")) .Result; if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } string subject = txtSubject.Text; string emailBody = htmlEmail.ResolvedValue; // Get event node data TreeProvider mTree = new TreeProvider(); DocTreeNode node = mTree.SelectSingleNode(EventID); if (node != null && CMSString.Equals(node.NodeClassName, "cms.bookingevent", true)) { // Initialize macro resolver MacroResolver resolver = MacroResolver.GetInstance(); resolver.Settings.KeepUnresolvedMacros = true; resolver.SetAnonymousSourceData(node); // Add named source data resolver.SetNamedSourceData("Event", node); // Event date string macro DateTime eventDate = ValidationHelper.GetDateTime(node.GetValue("EventDate"), DateTimeHelper.ZERO_TIME); DateTime eventEndDate = ValidationHelper.GetDateTime(node.GetValue("EventEndDate"), DateTimeHelper.ZERO_TIME); bool isAllDay = ValidationHelper.GetBoolean(node.GetValue("EventAllDay"), false); resolver.SetNamedSourceData("eventdatestring", EventProvider.GetEventDateString(eventDate, eventEndDate, isAllDay, TimeZoneHelper.GetTimeZoneInfo(SiteContext.CurrentSite), SiteContext.CurrentSiteName), false); // Resolve e-mail body and subject macros and make links absolute emailBody = resolver.ResolveMacros(emailBody); emailBody = URLHelper.MakeLinksAbsolute(emailBody); subject = TextHelper.LimitLength(resolver.ResolveMacros(subject), 450); // EventSendEmail manages sending e-mails to all attendees EventSendEmail ese = new EventSendEmail(EventID, SiteContext.CurrentSiteName, subject, emailBody, txtSenderName.Text.Trim(), txtSenderEmail.Text.Trim()); ShowConfirmation(GetString("Events_SendEmail.EmailSent")); } }
protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterJQuery(Page); ScriptHelper.RegisterModule(Page, "CMS.Content/LanguageMenu"); CSSHelper.RegisterCSSLink(Page, "~/CMSScripts/jquery/jquery-jscrollpane.css"); string currentSiteName = (SiteID != 0) ? SiteInfoProvider.GetSiteName(SiteID) : SiteContext.CurrentSiteName; var cultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName).Items; if (cultures.Count > 1) { string defaultCulture = CultureHelper.GetDefaultCultureCode(currentSiteName); CultureInfo ci = CultureInfoProvider.GetCultureInfo(SelectedCulture); imgLanguage.ImageUrl = GetFlagIconUrl(SelectedCulture, "16x16"); imgLanguage.AlternateText = imgLanguage.ToolTip = GetString(ci.CultureName); lblLanguageName.Text = ci.CultureShortName; // Generate sub-menu only if more cultures to choose from StringBuilder sb = new StringBuilder(); foreach (var culture in cultures) { string cultureCode = culture.CultureCode; string cultureName = HTMLHelper.HTMLEncode(culture.CultureName); if (CMSString.Compare(cultureCode, defaultCulture, true) == 0) { cultureName += " " + GetString("general.defaultchoice"); } string flagUrl = GetFlagIconUrl(cultureCode, "16x16"); var click = String.Format("ChangeLanguage({0}); return false;", ScriptHelper.GetString(cultureCode)); sb.AppendFormat("<li><a href=\"#\" onclick=\"{0}\"><img src=\"{1}\" alt=\"\" class=\"language-flag\"><span class=\"language-name\">{2}</span></a></li>", click, flagUrl, cultureName); } ltlLanguages.Text = sb.ToString(); // Split view button if (DisplayCompare) { btnCompare.ToolTip = GetString("SplitMode.CompareLangVersions"); btnCompare.Text = GetString("SplitMode.Compare"); if (UIContext.DisplaySplitMode) { btnCompare.AddCssClass("active"); } else { btnCompare.RemoveCssClass("active"); } } } else { // Hide language menu for one assigned culture on site Visible = false; } }
protected void libraryMenuElem_OnReloadData(object sender, EventArgs e) { var parameters = (libraryMenuElem.Parameter ?? string.Empty).Split(new [] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (parameters.Length == 2) { // Parse identifier and document culture from library parameter int nodeId = ValidationHelper.GetInteger(parameters[0], 0); string cultureCode = ValidationHelper.GetString(parameters[1], string.Empty); DocumentManager.Mode = FormModeEnum.Update; DocumentManager.ClearNode(); DocumentManager.DocumentID = 0; DocumentManager.NodeID = nodeId; DocumentManager.CultureCode = cultureCode; TreeNode node = DocumentManager.Node; bool contextMenuVisible = false; bool localizeVisible = false; bool editVisible = false; bool uploadVisible = false; bool copyVisible = false; bool deleteVisible = false; bool openVisible = false; bool propertiesVisible = false; bool permissionsVisible = false; bool versionHistoryVisible = false; bool checkOutVisible = false; bool checkInVisible = false; bool undoCheckoutVisible = false; bool submitToApprovalVisible = false; bool rejectVisible = false; bool archiveVisible = false; if ((node != null) && (!CheckPermissions || (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed))) { // Get original node (in case of linked documents) TreeNode originalNode = TreeProvider.GetOriginalNode(node); string siteName = SiteContext.CurrentSiteName; string currentDocumentCulture = DocumentContext.CurrentDocumentCulture.CultureCode; if (SiteContext.CurrentSiteID != originalNode.NodeSiteID) { SiteInfo si = SiteInfoProvider.GetSiteInfo(originalNode.NodeSiteID); siteName = si.SiteName; } if (!DocumentManager.ProcessingAction) { // Get permissions const bool authorizedToRead = true; bool authorizedToDelete = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Delete) == AuthorizationResultEnum.Allowed); bool authorizedToModify = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed); bool authorizedCultureToModify = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify, false) == AuthorizationResultEnum.Allowed) && TreeSecurityProvider.HasUserCultureAllowed(NodePermissionsEnum.Modify, currentDocumentCulture, MembershipContext.AuthenticatedUser, siteName); bool authorizedToModifyPermissions = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed); bool authorizedToCreate = MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(node.NodeParentID, node.NodeClassName); // Hide menu when user has no 'Read' permissions on document libraryMenuElem.Visible = authorizedToRead; // First evaluation of control's visibility bool differentCulture = (CMSString.Compare(node.DocumentCulture, currentDocumentCulture, true) != 0); localizeVisible = differentCulture && authorizedToCreate && authorizedCultureToModify; uploadVisible = authorizedToModify && DocumentManager.AllowSave; copyVisible = authorizedToCreate && authorizedToModify; deleteVisible = authorizedToDelete; openVisible = authorizedToRead; propertiesVisible = authorizedToModify; permissionsVisible = authorizedToModifyPermissions; versionHistoryVisible = authorizedToModify; editVisible = authorizedToModify; // Get next step info var stps = new List <WorkflowStepInfo>(); var workflow = DocumentManager.Workflow; bool basicWorkflow = true; if (workflow != null) { basicWorkflow = workflow.IsBasic; stps = WorkflowManager.GetNextStepInfo(node); } var appSteps = stps.FindAll(s => !s.StepIsArchived); var archSteps = stps.FindAll(s => s.StepIsArchived); // Workflow actions submitToApprovalVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.APPROVE) && (appSteps.Count > 0); rejectVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.REJECT); archiveVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.ARCHIVE) && ((archSteps.Count > 0) || basicWorkflow); checkOutVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKOUT); checkInVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKIN); undoCheckoutVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.UNDO_CHECKOUT); string parameterScript = "GetContextMenuParameter('" + libraryMenuElem.MenuID + "')"; // Initialize edit menu item Guid attachmentGuid = ValidationHelper.GetGuid(node.GetValue("FileAttachment"), Guid.Empty); // If attachment field doesn't allow empty value and the value is empty if ((FieldInfo != null) && !FieldInfo.AllowEmpty && (attachmentGuid == Guid.Empty)) { submitToApprovalVisible = false; archiveVisible = false; checkInVisible = false; } // Get attachment var ai = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, siteName, false); Panel currentPanel = pnlEdit; if (editVisible) { if (ai != null) { // Setup external editing var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlEditPadding, FileTypeEnum.Attachment, null, ai, IsLiveSite, node); if (ctrl != null) { ctrl.ID = "editAttachment"; ctrl.AttachmentFieldName = "FileAttachment"; ctrl.LabelText = GetString("general.edit"); ctrl.RefreshScript = JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'ExternalRefresh');"; ctrl.ReloadData(true); pnlEditPadding.CssClass = ctrl.EnabledResult ? "ItemPadding" : "ItemPaddingDisabled"; } else { pnlEditPadding.Visible = false; } } else { editVisible = false; openVisible = false; } } Panel previousPanel = currentPanel; currentPanel = pnlUpload; // Initialize upload menu item if (authorizedToModify) { // Initialize direct file uploader updateAttachment.Text = GetString("general.update"); updateAttachment.InnerElementClass = "LibraryContextUploader"; updateAttachment.DocumentID = node.DocumentID; updateAttachment.ParentElemID = ClientID; updateAttachment.SourceType = MediaSourceEnum.Attachment; updateAttachment.AttachmentGUIDColumnName = "FileAttachment"; updateAttachment.IsLiveSite = IsLiveSite; // Set allowed extensions if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom") { // Load allowed extensions updateAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], ""); } else { // Use site settings updateAttachment.AllowedExtensions = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSUploadExtensions"); } updateAttachment.ReloadData(); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlLocalize; // Initialize localize menu item if (localizeVisible) { lblLocalize.RefreshText(); pnlLocalize.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Localize');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = null; currentPanel = pnlCopy; // Initialize copy menu item if (copyVisible) { lblCopy.RefreshText(); pnlCopy.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ",'Copy');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlDelete; // Initialize delete menu item if (deleteVisible) { lblDelete.RefreshText(); pnlDelete.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Delete');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlOpen; // Initialize open menu item if (openVisible) { lblOpen.RefreshText(); if (ai != null) { // Get document URL string attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(node.NodeGUID, node.NodeAlias)); if (authorizedToModify) { attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(node.DocumentID, string.Empty)); attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + node.DocumentID)); } attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString()); if (!string.IsNullOrEmpty(attachmentUrl)) { pnlOpen.Attributes.Add("onclick", "location.href = " + ScriptHelper.GetString(attachmentUrl) + ";"); } } SetupPanelClasses(currentPanel, previousPanel); } previousPanel = null; currentPanel = pnlProperties; // Initialize properties menu item lblProperties.RefreshText(); pnlProperties.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Properties');"); SetupPanelClasses(currentPanel, previousPanel); previousPanel = currentPanel; currentPanel = pnlPermissions; // Initialize permissions menu item lblPermissions.RefreshText(); pnlPermissions.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Permissions');"); SetupPanelClasses(currentPanel, previousPanel); previousPanel = currentPanel; currentPanel = pnlVersionHistory; // Initialize version history menu item lblVersionHistory.RefreshText(); pnlVersionHistory.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'VersionHistory');"); SetupPanelClasses(currentPanel, previousPanel); previousPanel = null; currentPanel = pnlCheckOut; // Initialize checkout menu item if (checkOutVisible) { lblCheckOut.RefreshText(); pnlCheckOut.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckOut');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlCheckIn; // Initialize check in menu item if (checkInVisible) { lblCheckIn.RefreshText(); pnlCheckIn.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckIn');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlUndoCheckout; // Initialize undo checkout menu item if (undoCheckoutVisible) { lblUndoCheckout.RefreshText(); pnlUndoCheckout.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'UndoCheckout');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlSubmitToApproval; // Initialize submit to approval / publish menu item if (submitToApprovalVisible) { // Only one next step if (appSteps.Count == 1) { if (appSteps[0].StepIsPublished) { // Set 'Publish' label lblSubmitToApproval.ResourceString = "general.publish"; cmcApp.Parameter = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.PUBLISH); } pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'SubmitToApproval');"); } // Multiple steps - display dialog else { pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new [] { "'" + DocumentComponentEvents.APPROVE + "'", node.DocumentID.ToString() }), null) + ";"); cmcApp.Enabled = false; } lblSubmitToApproval.RefreshText(); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlReject; // Initialize reject menu item if (rejectVisible) { lblReject.RefreshText(); pnlReject.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Reject');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlArchive; // Initialize archive menu item if (archiveVisible) { // Only one archive step if ((archSteps.Count == 1) || basicWorkflow) { pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Archive');"); } // Multiple archive steps - display dialog else { pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new [] { "'" + DocumentComponentEvents.ARCHIVE + "'", node.DocumentID.ToString() }), null) + ";"); cmcArch.Enabled = false; } lblArchive.RefreshText(); SetupPanelClasses(currentPanel, previousPanel); } // Set up visibility of menu items pnlLocalize.Visible = localizeVisible; pnlUpload.Visible = uploadVisible; pnlDelete.Visible = deleteVisible; pnlCopy.Visible = copyVisible; pnlOpen.Visible = openVisible; pnlProperties.Visible = propertiesVisible; pnlPermissions.Visible = permissionsVisible; pnlVersionHistory.Visible = versionHistoryVisible; pnlEdit.Visible = editVisible; pnlCheckOut.Visible = checkOutVisible; pnlCheckIn.Visible = checkInVisible; pnlUndoCheckout.Visible = undoCheckoutVisible; pnlSubmitToApproval.Visible = submitToApprovalVisible; pnlReject.Visible = rejectVisible; pnlArchive.Visible = archiveVisible; // Set up visibility of whole menu contextMenuVisible = true; } if (DocumentManager.ProcessingAction) { // Setup 'No action available' menu item pnlNoAction.Visible = true; lblNoAction.ResourceString = null; lblNoAction.Text = DocumentManager.GetDocumentInfo(true); lblNoAction.RefreshText(); } else { // Set up visibility of separators bool firstGroupVisible = editVisible || uploadVisible || localizeVisible; bool secondGroupVisible = copyVisible || deleteVisible || openVisible; bool thirdGroupVisible = propertiesVisible || permissionsVisible || versionHistoryVisible; bool fourthGroupVisible = checkOutVisible || checkInVisible || undoCheckoutVisible || submitToApprovalVisible || rejectVisible || archiveVisible; pnlSep1.Visible = firstGroupVisible && secondGroupVisible; pnlSep2.Visible = secondGroupVisible && thirdGroupVisible; pnlSep3.Visible = thirdGroupVisible && fourthGroupVisible; // Setup 'No action available' menu item pnlNoAction.Visible = !contextMenuVisible; lblNoAction.RefreshText(); } } } }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Trim blank space and too long string string codeName = txtCodeName.Text.Trim(); if (codeName.Length > 200) { codeName = codeName.Substring(0, 200); } // Get code name codeName = ValidationHelper.GetCodeName(codeName, null, null); txtCodeName.Text = codeName; // Perform validation string errorMessage = new Validator().NotEmpty(codeName, rfvCodeName.ErrorMessage) .NotEmpty(txtDisplayName.Text, rfvDisplayName.ErrorMessage).Result; // Check CodeName for identifier format if (!ValidationHelper.IsCodeName(codeName)) { errorMessage = GetString("General.ErrorCodeNameInIdentifierFormat"); } // Check length of code name if (codeName.Length > codeNameLength) { errorMessage = GetString("srch.codenameexceeded"); } if (errorMessage == "") { // Check code name SearchIndexInfo sii = SearchIndexInfoProvider.GetSearchIndexInfo(codeName); // Get current item SearchIndexInfo current = SearchIndexInfoProvider.GetSearchIndexInfo(ItemID); // Check if code name is unique if ((sii == null) || (sii == current)) { // Get original index path string originalPath = current.CurrentIndexPath; // Set the fields current.IndexName = codeName; // Trim blank space and too long string txtDisplayName.Text = txtDisplayName.Text.Trim(); if (txtDisplayName.Text.Length > 200) { txtDisplayName.Text = txtDisplayName.Text.Substring(0, 200); } if (current.IndexDisplayName != txtDisplayName.Text) { // Refresh a breadcrumb if used in the tabs layout ScriptHelper.RefreshTabHeader(Page, string.Empty); } current.IndexDisplayName = txtDisplayName.Text; // Check if analyzer type is changed bool analyzerTypeChanged = false; if ((current != null) && ((current.IndexAnalyzerType != SearchIndexInfoProvider.AnalyzerCodenameToEnum(drpAnalyzer.SelectedValue)) || (CMSString.Compare(current.StopWordsFile, stopCustomControl.StopWordsFile, true) != 0) || (CMSString.Compare(current.CustomAnalyzerAssemblyName, stopCustomControl.CustomAnalyzerAssemblyName, true) != 0) || (CMSString.Compare(current.CustomAnalyzerClassName, stopCustomControl.CustomAnalyzerClassName, true) != 0))) { analyzerTypeChanged = true; } current.IndexAnalyzerType = SearchIndexInfoProvider.AnalyzerCodenameToEnum(drpAnalyzer.SelectedValue); // Community indexing is not yet supported //current.IndexIsCommunityGroup = chkCommunity.Checked; current.IndexIsCommunityGroup = false; current.CustomAnalyzerAssemblyName = stopCustomControl.CustomAnalyzerAssemblyName; current.CustomAnalyzerClassName = stopCustomControl.CustomAnalyzerClassName; current.StopWordsFile = stopCustomControl.StopWordsFile; current.IndexBatchSize = ValidationHelper.GetInteger(txtBatchSize.Text, 10); // Save the object SearchIndexInfoProvider.SetSearchIndexInfo(current); // Codename changed bool codenameChanged = false; if (sii == null) { try { DirectoryHelper.MoveDirectory(originalPath, current.CurrentIndexPath); } catch (Exception ex) { EventLogProvider ep = new EventLogProvider(); ep.LogEvent("SmartSearch", "Rename", ex); } codenameChanged = true; } ShowChangesSaved(); if (codenameChanged || analyzerTypeChanged) { ShowInformation(String.Format(GetString("srch.indexrequiresrebuild"), "<a href=\"javascript:" + Page.ClientScript.GetPostBackEventReference(this, "saved") + "\">" + GetString("General.clickhere") + "</a>")); } // Redirect to edit mode RaiseOnSaved(); } else { // Error message - code name already exists ShowError(GetString("srch.index.codenameexists")); } } else { // Error message - validation ShowError(errorMessage); } }