public void ReloadData(bool force) { if (DeletedNode != null) { if (!RequestHelper.IsPostBack() || force) { plcConfirmation.Visible = true; } // Display confirmation lblConfirmation.Text = string.Format(GetString("contentdelete.questionspecific"), DeletedNode.NodeName); // Set visibility of 'delete all cultures' checkbox string currentSiteName = SiteContext.CurrentSiteName; chkAllCultures.Visible = CultureSiteInfoProvider.IsSiteMultilingual(currentSiteName); if (MembershipContext.AuthenticatedUser.UserHasAllowedCultures) { DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName); foreach (DataRow culture in siteCultures.Tables[0].Rows) { string cultureCode = ValidationHelper.GetString(DataHelper.GetDataRowValue(culture, "CultureCode"), string.Empty); if (!MembershipContext.AuthenticatedUser.IsCultureAllowed(cultureCode, currentSiteName)) { chkAllCultures.Visible = false; break; } } } } Visible = (DeletedNode != null); btnCancel.Text = GetString("general.cancel"); }
/// <summary> /// Handles the PathChanged event of the ucPath control. /// </summary> protected void ucPath_PathChanged(object sender, EventArgs ea) { string[] parameters = SessionHelper.GetValue(PreviewObjectName) as string[]; // Get old site ID int SiteID = SiteContext.CurrentSiteID; if ((parameters != null) && (parameters.Length == 4)) { SiteID = ValidationHelper.GetInteger(parameters[1], 0); } // If site ID changed - register postback for reload update panel with culture selector if (SiteID != ucPath.SiteID) { String script = Page.ClientScript.GetPostBackEventReference(imgRefresh, "reloadculture"); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "UpdateImageScript", script, true); // If cultures from other site is shown DataSet siteCulturesDS = CultureSiteInfoProvider.GetSiteCultures(SiteInfoProvider.GetSiteName(ucPath.SiteID)); if (!DataHelper.DataSourceIsEmpty(siteCulturesDS)) { DataTable siteCultures = siteCulturesDS.Tables[0]; // SelectedCulture may not be in site culture list DataRow[] dr = siteCulturesDS.Tables[0].Select("CultureCode= '" + ucSelectCulture.SelectedCulture + "'"); if (dr.Length == 0) { // In such case, select first site's culture ucSelectCulture.SelectedCulture = ValidationHelper.GetString(siteCultures.Rows[0]["CultureCode"], MembershipContext.AuthenticatedUser.PreferredCultureCode); } } } UpdatePreview(true); }
public IEnumerable <SiteCulture> GetAll() { var siteName = _siteService.CurrentSite.SiteName; return(CultureSiteInfoProvider.GetSiteCultures(siteName) .Select(culture => MapDtoProperties(culture, siteName))); }
protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterJQuery(Page); ScriptHelper.RegisterModule(Page, "CMS/ScrollPane", new { selector = "#language-menu" }); CssRegistration.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 = CultureInfo.Provider.Get(SelectedCulture); imgLanguage.ImageUrl = GetFlagIconUrl(SelectedCulture, "16x16"); imgLanguage.AlternateText = imgLanguage.ToolTip = ResHelper.LocalizeString(ci.CultureName); lblLanguageName.Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(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(ResHelper.LocalizeString(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 btnCompare.ToolTip = GetString("SplitMode.CompareLangVersions"); btnCompare.Text = GetString("SplitMode.Compare"); if (PortalUIHelper.DisplaySplitMode) { btnCompare.AddCssClass("active"); } else { btnCompare.RemoveCssClass("active"); } } else { // Hide language menu for one assigned culture on site Visible = false; } }
public IEnumerable <CultureDto> GetSiteCultures() { return(CultureSiteInfoProvider.GetSiteCultures(SiteContextService.SiteName).Items.Select(m => new CultureDto() { CultureCode = m.CultureCode, CultureName = m.CultureName, CultureShortName = m.CultureShortName } )); }
public IEnumerable <CultureDto> GetSiteCultures() => CultureSiteInfoProvider.GetSiteCultures(SiteContextService.SiteName) .Items .Select(culture => new CultureDto() { CultureGuid = culture.CultureGUID, CultureCode = culture.CultureCode, CultureName = culture.CultureName, CultureShortName = culture.CultureShortName } );
/// <inheritdoc /> public IEnumerable <ICulture> GetSiteCultures(ISite site) { List <ICulture> cultures = new List <ICulture>(); SiteInfo siteToWork = SiteInfoProvider.GetSiteInfo(site.SiteName); if (siteToWork != null) { var items = CultureSiteInfoProvider.GetSiteCultures(site.SiteName)?.Items; foreach (var item in items) { cultures.Add(item.ActLike <ICulture>()); } } return(cultures); }
public static SiteCulture?ToSiteCulture(this CultureInfo cultureInfo) { var siteName = SiteContext.CurrentSiteName; if (cultureInfo != null && CultureSiteInfoProvider.IsCultureOnSite(cultureInfo.Name, siteName)) { var culture = CultureSiteInfoProvider .GetSiteCultures(siteName) .FirstOrDefault(culture => culture.CultureCode.Equals(cultureInfo.Name, StringComparison.InvariantCulture)); if (culture != null) { return(SiteCultureRepository.MapDtoProperties(culture, siteName)); } } return(null); }
public async Task SyncCultures() { try { SyncLog.Log("Synchronizing cultures"); SyncLog.LogEvent(EventType.INFORMATION, "KenticoKontentPublishing", "SYNCCULTURES"); var existingLanguages = await GetAllLanguages(); var cultures = CultureSiteInfoProvider.GetSiteCultures(Settings.Sitename).ToList(); await PatchDefaultLanguage(); // Deactivate all unknown languages to make sure they don't conflict with the active ones foreach (var language in existingLanguages) { if (language.IsActive && (language.Id != Guid.Empty) && !cultures.Exists(culture => GetLanguageExternalId(culture.CultureGUID).Equals(language.ExternalId))) { await DeactivateLanguage(language); } } // Create or update all known languages foreach (var culture in cultures) { if (existingLanguages.Exists(language => language.ExternalId?.Equals(GetLanguageExternalId(culture.CultureGUID)) == true)) { await PatchLanguage(culture); } else { await CreateLanguage(culture); } } } catch (Exception ex) { SyncLog.LogException("KenticoKontentPublishing", "SYNCCULTURES", ex); throw; } }
/// <summary> /// Hides culture button for less than two site cultures /// </summary> private void ReplaceCultureButton(List <Group> groups) { // Replace Culture button Group culture = groups.Find(g => g.CssClass.Contains("OnSiteCultures")); if (culture != null) { // Hide culture selector when there is only one culture for the current site InfoDataSet <CultureInfo> sites = CultureSiteInfoProvider.GetSiteCultures(SiteContext.CurrentSiteName); if (sites.Tables[0].Rows.Count < 2) { // Remove the culture button groups.Remove(culture); } else { culture.ControlPath = "~/CMSAdminControls/UI/UniMenu/OnSiteEdit/CultureMenu.ascx"; } } }
/// <summary> /// Handles Unigrid's ExternalDataBound event. /// </summary> /// <param name="sender">Sender</param> /// <param name="sourceName">Source name</param> /// <param name="parameter">Parameter</param> protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLowerCSafe()) { case "path": var encodedParam = HTMLHelper.HTMLEncode(parameter.ToString()); string result = UIHelper.GetAccessibleIconTag("icon-exclamation-triangle", GetString("abtesting.variantculturewarning"), FontIconSizeEnum.NotDefined, "warning-icon") + " " + encodedParam; if (ABTest != null) { // If AB test is for specified culture if (!string.IsNullOrEmpty(ABTest.ABTestCulture)) { // Try to find document in required culture if (TreeProvider.SelectSingleNode(SiteContext.CurrentSiteName, parameter.ToString(), ABTest.ABTestCulture, false, null, false) != null) { return(parameter); } } else { // For all cultures, compare number of site cultures and number of variant translations var siteCultures = CultureSiteInfoProvider.GetSiteCultures(SiteContext.CurrentSiteName).Items.Count; var nodeCultures = DocumentHelper.GetDocuments() .PublishedVersion() .All() .OnCurrentSite() .AllCultures() .Column("DocumentCulture") .WhereEquals("NodeAliasPath", parameter.ToString()) .Count(); return((siteCultures != nodeCultures) ? result : encodedParam); } } return(result); } return(parameter); }
private int GetNumberOfCurrentSiteCultures() { return(CultureSiteInfoProvider.GetSiteCultures(SiteContext.CurrentSiteName).Tables[0].Rows.Count); }
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.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && !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")); } }
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())); }
protected DataSet gridDocuments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { if (Node == null) { return(null); } // Get documents string currentSiteName = SiteContext.CurrentSiteName; int topN = gridLanguages.GridView.PageSize * (gridLanguages.GridView.PageIndex + 1 + gridLanguages.GridView.PagerSettings.PageButtonCount); columns = SqlHelper.MergeColumns(SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, columns), "DocumentModifiedWhen, DocumentLastVersionNumber, DocumentLastPublished, DocumentIsWaitingForTranslation"); var query = DocumentHelper.GetDocuments() .OnSite(currentSiteName) .Path(Node.NodeAliasPath) .AllCultures() .Published(false) .TopN(topN) .Columns(columns); // Do not apply published from / to columns to make sure the published information is correctly evaluated query.Properties.ExcludedVersionedColumns = new[] { "DocumentPublishFrom", "DocumentPublishTo" }; var data = query.Result; if (DataHelper.DataSourceIsEmpty(data)) { return(null); } var documents = data.Tables[0]; // Get site cultures var allSiteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName).Copy(); // Rename culture column to enable row transfer allSiteCultures.Tables[0].Columns[2].ColumnName = "DocumentCulture"; // Create where condition for row transfer string where = documents.Rows.Cast <DataRow>().Aggregate("DocumentCulture NOT IN (", (current, row) => current + ("'" + SqlHelper.EscapeQuotes(ValidationHelper.GetString(row["DocumentCulture"], string.Empty)) + "',")); where = where.TrimEnd(',') + ")"; // Transfer missing cultures, keep original list of site cultures DataHelper.TransferTableRows(documents, allSiteCultures.Copy().Tables[0], where, null); DataHelper.EnsureColumn(documents, "DocumentCultureDisplayName", typeof(string)); // Ensure culture names foreach (DataRow cultDR in documents.Rows) { string cultureCode = cultDR["DocumentCulture"].ToString(); DataRow[] cultureRow = allSiteCultures.Tables[0].Select("DocumentCulture='" + cultureCode + "'"); if (cultureRow.Length > 0) { cultDR["DocumentCultureDisplayName"] = cultureRow[0]["CultureName"].ToString(); } } // Ensure default culture to be first DataRow[] cultureDRs = documents.Select("DocumentCulture='" + DefaultSiteCulture + "'"); if (cultureDRs.Length <= 0) { throw new Exception("[ReloadData]: Default site culture '" + DefaultSiteCulture + "' is not assigned to the current site."); } DataRow defaultCultureRow = cultureDRs[0]; DataRow dr = documents.NewRow(); dr.ItemArray = defaultCultureRow.ItemArray; documents.Rows.InsertAt(dr, 0); documents.Rows.Remove(defaultCultureRow); // Get last modification date of default culture defaultCultureRow = documents.Select("DocumentCulture='" + DefaultSiteCulture + "'")[0]; defaultLastModification = ValidationHelper.GetDateTime(defaultCultureRow["DocumentModifiedWhen"], DateTimeHelper.ZERO_TIME); defaultLastPublished = ValidationHelper.GetDateTime(defaultCultureRow["DocumentLastPublished"], DateTimeHelper.ZERO_TIME); // Add column containing translation status documents.Columns.Add("TranslationStatus", typeof(TranslationStatusEnum)); // Get proper translation status and store it to datatable foreach (DataRow document in documents.Rows) { TranslationStatusEnum status; int documentId = ValidationHelper.GetInteger(document["DocumentID"], 0); if (documentId == 0) { status = TranslationStatusEnum.NotAvailable; } else { string versionNumber = DataHelper.GetStringValue(document, "DocumentLastVersionNumber", null); if (ValidationHelper.GetBoolean(document["DocumentIsWaitingForTranslation"], false)) { status = TranslationStatusEnum.WaitingForTranslation; } else { DateTime lastModification; // Check if document is outdated if (versionNumber != null) { lastModification = ValidationHelper.GetDateTime(document["DocumentLastPublished"], DateTimeHelper.ZERO_TIME); status = (lastModification < defaultLastPublished) ? TranslationStatusEnum.Outdated : TranslationStatusEnum.Translated; } else { lastModification = ValidationHelper.GetDateTime(document["DocumentModifiedWhen"], DateTimeHelper.ZERO_TIME); status = (lastModification < defaultLastModification) ? TranslationStatusEnum.Outdated : TranslationStatusEnum.Translated; } } } document["TranslationStatus"] = status; } // Bind datasource DataSet filteredDocuments = data.Clone(); DataRow[] filteredDocs = documents.Select(gridLanguages.GetFilter()); foreach (DataRow row in filteredDocs) { filteredDocuments.Tables[0].ImportRow(row); } return(filteredDocuments); }
protected void Page_Load(object sender, EventArgs e) { // Register script files ScriptHelper.RegisterCMS(this); ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js"); // Set current UI culture currentCulture = CultureHelper.PreferredUICultureCode; // Initialize current user currentUser = MembershipContext.AuthenticatedUser; // Initialize current site currentSite = SiteContext.CurrentSite; // Initialize events ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; if (!RequestHelper.IsCallback()) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(currentUser); btnCancel.Text = GetString("general.cancel"); // Current Node ID to delete string parentAliasPath = string.Empty; if (Parameters != null) { parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty); } if (string.IsNullOrEmpty(parentAliasPath)) { nodeIdsArr = QueryHelper.GetString("nodeid", string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } } else { string where = "ClassName <> 'CMS.Root'"; if (!string.IsNullOrEmpty(WhereCondition)) { where = SqlHelper.AddWhereCondition(where, WhereCondition); } allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%", TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where, "DocumentName", TreeProvider.ALL_LEVELS, false, 0, TreeProvider.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath,NodeSKUID"); if (!DataHelper.DataSourceIsEmpty(allDocs)) { foreach (DataTable table in allDocs.Tables) { foreach (DataRow row in table.Rows) { nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0)); } } } } // Setup page title text and image PageTitle.TitleText = GetString("Content.DeleteTitle"); EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText); btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); // Register the dialog script ScriptHelper.RegisterDialogScript(this); titleElemAsync.TitleText = GetString("ContentDelete.DeletingDocuments"); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; bool isMultilingual = CultureSiteInfoProvider.IsSiteMultilingual(currentSite.SiteName); if (!isMultilingual) { // Set all cultures checkbox chkAllCultures.Checked = true; chkAllCultures.Visible = false; } if (nodeIds.Count > 0) { if (nodeIds.Count == 1) { // Single document deletion int nodeId = ValidationHelper.GetInteger(nodeIds[0], 0); TreeNode node = null; if (string.IsNullOrEmpty(parentAliasPath)) { // Get any culture if current not found node = tree.SelectSingleNode(nodeId, CultureCode) ?? tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); } else { if (allDocs != null) { DataRow dr = allDocs.Tables[0].Rows[0]; node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr, tree); } } if (node != null) { bool rootDeleteDisabled = false; if (IsProductsMode) { string startingPath = SettingsKeyInfoProvider.GetStringValue(CurrentSiteName + ".CMSStoreProductsStartingPath"); if (node.NodeAliasPath.CompareToCSafe(startingPath) == 0) { string closeLink = "<a href=\"#\"><span style=\"cursor: pointer;\" " + "onclick=\"SelectNode(" + node.NodeID + "); return false;\">" + GetString("general.back") + "</span></a>"; ShowError(string.Format(GetString("com.productsection.deleteroot"), closeLink, "")); pnlDelete.Visible = false; rootDeleteDisabled = true; } } if (node.IsRoot() && isMultilingual) { // Hide 'Delete all cultures' checkbox chkAllCultures.Visible = false; if (!URLHelper.IsPostback()) { // Check if there are any documents in another culture or current culture has some documents pnlDeleteRoot.Visible = IsAnyDocumentInAnotherCulture(node) && (tree.SelectNodesCount(SiteContext.CurrentSiteName, "/%", LocalizationContext.PreferredCultureCode, false, null, null, null, TreeProvider.ALL_LEVELS, false) > 0); if (pnlDeleteRoot.Visible) { // Insert 'Delete current root' option if current root node is translated to current culture if (node.DocumentCulture == LocalizationContext.PreferredCultureCode) { rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentroot"), "current")); } rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentculture"), "allculturepages")); rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages")); } else { rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages")); } if (rblRoot.SelectedIndex < 0) { rblRoot.SelectedIndex = 0; } } } // Display warning for root node if (!rootDeleteDisabled && node.IsRoot()) { if (!currentUser.IsGlobalAdministrator) { pnlDelete.Visible = false; ShowInformation(GetString("delete.rootonlyglobaladmin")); } else { if ((rblRoot.SelectedValue == "allpages") || !isMultilingual || ((rblRoot.SelectedValue == "allculturepages") && !IsAnyDocumentInAnotherCulture(node))) { messagesPlaceholder.ShowWarning(GetString("Delete.RootWarning")); plcDeleteRoot.Visible = true; } else { plcDeleteRoot.Visible = false; } } } hasChildren = node.NodeHasChildren; bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node); if (!RequestHelper.IsPostBack()) { bool authorizedToDeleteDocument = IsUserAuthorizedToDeleteDocument(node); if (!authorizedToDeleteDocument || !authorizedToDeleteSKU) { pnlDelete.Visible = false; RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath))); } } if (node.IsLink) { PageTitle.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(node.GetDocumentName())) + "\""; headQuestion.Text = GetString("ContentDelete.QuestionLink"); chkAllCultures.Checked = true; plcCheck.Visible = false; } else { string nodeName = HTMLHelper.HTMLEncode(node.GetDocumentName()); // Get name for root document if (node.NodeClassName.ToLowerCSafe() == "cms.root") { nodeName = HTMLHelper.HTMLEncode(currentSite.DisplayName); } PageTitle.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(nodeName)) + "\""; bool showSKUGroup = false; if (NodeHasChildWithProduct(tree, node)) { // Deleting product section lblSKUActionInfo.Text = GetString("ContentDelete.SectionAssignedSKUInfo"); headDeleteSKU.Text = GetString("ContentDelete.AssignedSKUs"); showSKUGroup = true; } else if (node.HasSKU && authorizedToDeleteSKU) { // Deleting product if (!NodeSharesSKUWithOtherNode(tree, node)) { lblSKUActionInfo.Text = GetString("contentdelete.assignedskuinfo"); headDeleteSKU.Text = GetString("ContentDelete.AssignedSKU"); showSKUGroup = true; } } pnlDeleteSKU.Visible = showSKUGroup; rblSKUAction.Visible = showSKUGroup; } // Show or hide checkbox chkDestroy.Visible = CanDestroy(node); cancelNodeId = IsMultipleAction ? node.NodeParentID : node.NodeID; if (node.IsRoot()) { // Change SEO panel if root is selected pnlSeo.Visible = false; } } else { if (!RequestHelper.IsPostBack()) { URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists")); } else { // Hide everything pnlContent.Visible = false; } } headQuestion.Text = GetString("ContentDelete.Question"); chkAllCultures.Text = GetString("ContentDelete.AllCultures"); chkDestroy.Text = GetString("ContentDelete.Destroy"); headDeleteDocument.Text = GetString("ContentDelete.Document"); } else if (nodeIds.Count > 1) { pnlDocList.Visible = true; string where = "NodeID IN ("; foreach (int nodeID in nodeIds) { where += nodeID + ","; } where = where.TrimEnd(',') + ")"; DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", -1, false); if (!DataHelper.DataSourceIsEmpty(ds)) { string docList = null; if (string.IsNullOrEmpty(parentAliasPath)) { cancelNodeId = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeParentID"), 0); } else { cancelNodeId = TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath); } bool canDestroy = true; bool permissions = true; foreach (DataTable table in ds.Tables) { foreach (DataRow dr in table.Rows) { bool isLink = (dr["NodeLinkedNodeID"] != DBNull.Value); string name = (string)dr["DocumentName"]; docList += HTMLHelper.HTMLEncode(name); if (isLink) { docList += DocumentHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link); } docList += "<br />"; lblDocuments.Text = docList; // Set visibility of checkboxes TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr); if (!IsUserAuthorizedToDeleteDocument(node)) { permissions = false; AddError(String.Format( GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)), null); } // Can destroy if "can destroy all previous AND current" canDestroy = CanDestroy(node) && canDestroy; if (!hasChildren) { hasChildren = node.NodeHasChildren; } if ((node.HasSKU && IsUserAuthorizedToModifySKU(node)) || NodeHasChildWithProduct(tree, node)) { pnlDeleteSKU.Visible = true; rblSKUAction.Visible = true; } } } pnlDelete.Visible = permissions; chkDestroy.Visible = canDestroy; } else { if (!RequestHelper.IsPostBack()) { URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists")); } else { // Hide everything pnlContent.Visible = false; } } headQuestion.Text = GetString("ContentDelete.QuestionMultiple"); PageTitle.TitleText = GetString("Content.DeleteTitleMultiple"); chkAllCultures.Text = GetString("ContentDelete.AllCulturesMultiple"); chkDestroy.Text = GetString("ContentDelete.DestroyMultiple"); headDeleteDocument.Text = GetString("global.pages"); headDeleteSKU.Text = GetString("ContentDelete.AssignedSKUs"); lblSKUActionInfo.Text = GetString("ContentDelete.AssignedSKUsInfo"); } // Init product actions if (!RequestHelper.IsPostBack()) { rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.deleteordisable"), "deleteordisable")); rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.delete"), "delete")); rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.disable"), "disable")); rblSKUAction.Items.Add(new ListItem(GetString("ContentDelete.SKU.noaction"), "noaction")); rblSKUAction.SelectedValue = "deleteordisable"; } lblAltPath.AssociatedControlClientID = selAltPath.PathTextBox.ClientID; chkUseDeletedPath.CheckedChanged += chkUseDeletedPath_CheckedChanged; if (!RequestHelper.IsPostBack()) { selAltPath.Enabled = false; chkAltSubNodes.Enabled = false; chkAltAliases.Enabled = false; // Set default path if is defined selAltPath.Value = SettingsKeyInfoProvider.GetStringValue(CurrentSiteName + ".CMSDefaultDeletedNodePath"); if (!hasChildren) { chkAltSubNodes.Checked = false; chkAltSubNodes.Enabled = false; } } // If user has allowed cultures specified if (currentUser.UserHasAllowedCultures) { // Get all site cultures DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSite.SiteName); bool denyAllCulturesDeletion = false; // Check that user can edit all site cultures foreach (DataRow culture in siteCultures.Tables[0].Rows) { string cultureCode = ValidationHelper.GetString(DataHelper.GetDataRowValue(culture, "CultureCode"), string.Empty); if (!currentUser.IsCultureAllowed(cultureCode, currentSite.SiteName)) { denyAllCulturesDeletion = true; } } // If user can't edit all site cultures if (denyAllCulturesDeletion) { // Hide all cultures selector chkAllCultures.Visible = false; chkAllCultures.Checked = false; } } pnlDeleteDocument.Visible = chkAllCultures.Visible || chkDestroy.Visible; } else { // Hide everything pnlContent.Visible = false; } } }
/// <summary> /// Reloads control. /// </summary> /// <param name="forceReload">Forces nested CMSForm to reload if true</param> public void ReloadData(bool forceReload) { if (!mFormLoaded || forceReload) { // Check License LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.UserContributions); if (!StopProcessing) { // Set document manager mode if (NewDocument) { DocumentManager.Mode = FormModeEnum.Insert; DocumentManager.ParentNodeID = NodeID; DocumentManager.NewNodeClassID = ClassID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; } else if (NewCulture) { DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion; DocumentManager.NodeID = NodeID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; DocumentManager.SourceDocumentID = CopyDefaultDataFromDocumentID; } else { DocumentManager.Mode = FormModeEnum.Update; DocumentManager.NodeID = NodeID; DocumentManager.SiteName = SiteName; DocumentManager.CultureCode = CultureCode; } ScriptHelper.RegisterDialogScript(Page); titleElem.TitleText = String.Empty; pnlSelectClass.Visible = false; pnlEdit.Visible = false; pnlInfo.Visible = false; pnlNewCulture.Visible = false; pnlDelete.Visible = false; // If node found, init the form if (NewDocument || (Node != null)) { // Delete action if (Delete) { // Delete document pnlDelete.Visible = true; titleElem.TitleText = GetString("Content.DeleteTitle"); chkAllCultures.Text = GetString("ContentDelete.AllCultures"); chkDestroy.Text = GetString("ContentDelete.Destroy"); lblQuestion.Text = GetString("ContentDelete.Question"); btnYes.Text = GetString("general.yes"); // Prevent button double-click btnYes.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled=true;this.disabled=true;{1};", btnNo.ClientID, ControlsHelper.GetPostBackEventReference(btnYes, string.Empty, true, false))); btnNo.Text = GetString("general.no"); DataSet culturesDS = CultureSiteInfoProvider.GetSiteCultures(SiteName); if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1)) { chkAllCultures.Visible = false; chkAllCultures.Checked = true; } if (Node.IsLink) { titleElem.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\""; lblQuestion.Text = GetString("ContentDelete.QuestionLink"); chkAllCultures.Checked = true; plcCheck.Visible = false; } else { titleElem.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\""; } } // New document or edit action else { if (NewDocument) { titleElem.TitleText = GetString("Content.NewTitle"); } // Document type selection if (NewDocument && (ClassID <= 0)) { // Use parent node TreeNode parentNode = DocumentManager.ParentNode; if (parentNode != null) { // Select document type pnlSelectClass.Visible = true; // Apply document type scope string whereCondition = DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(parentNode); var parentClassId = ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0); var siteId = SiteInfoProvider.GetSiteID(SiteName); // Get the allowed child classes DataSet ds = AllowedChildClassInfoProvider.GetAllowedChildClasses(parentClassId, siteId) .Where(whereCondition) .OrderBy("ClassID") .Columns("ClassName", "ClassDisplayName", "ClassID"); ArrayList deleteRows = new ArrayList(); if (!DataHelper.DataSourceIsEmpty(ds)) { // Get the unwanted classes string allowed = AllowedChildClasses.Trim().ToLowerCSafe(); if (!string.IsNullOrEmpty(allowed)) { allowed = String.Format(";{0};", allowed); } var userInfo = MembershipContext.AuthenticatedUser; string className = null; // Check if the user has 'Create' permission per Content bool isAuthorizedToCreateInContent = userInfo.IsAuthorizedPerResource("CMS.Content", "Create"); bool hasNodeAllowCreate = (userInfo.IsAuthorizedPerTreeNode(parentNode, NodePermissionsEnum.Create) != AuthorizationResultEnum.Allowed); foreach (DataRow dr in ds.Tables[0].Rows) { className = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "ClassName"), String.Empty).ToLowerCSafe(); // Document type is not allowed or user hasn't got permission, remove it from the data set if ((!string.IsNullOrEmpty(allowed) && (!allowed.Contains(";" + className + ";"))) || (CheckPermissions && CheckDocPermissionsForInsert && !isAuthorizedToCreateInContent && !userInfo.IsAuthorizedPerClassName(className, "Create") && (!userInfo.IsAuthorizedPerClassName(className, "CreateSpecific") || !hasNodeAllowCreate))) { deleteRows.Add(dr); } } // Remove the rows foreach (DataRow dr in deleteRows) { ds.Tables[0].Rows.Remove(dr); } } // Check if some classes are available if (!DataHelper.DataSourceIsEmpty(ds)) { // If number of classes is more than 1 display them in grid if (ds.Tables[0].Rows.Count > 1) { ds.Tables[0].DefaultView.Sort = "ClassDisplayName"; lblError.Visible = false; lblInfo.Visible = true; lblInfo.Text = GetString("Content.NewInfo"); DataSet sortedResult = new DataSet(); sortedResult.Tables.Add(ds.Tables[0].DefaultView.ToTable()); gridClass.DataSource = sortedResult; gridClass.ReloadData(); } // else show form of the only class else { ClassID = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "ClassID"), 0); ReloadData(true); return; } } else { // Display error message lblError.Visible = true; lblError.Text = GetString("Content.NoAllowedChildDocuments"); lblInfo.Visible = false; gridClass.Visible = false; } } else { pnlInfo.Visible = true; lblFormInfo.Text = GetString("EditForm.DocumentNotFound"); } } // Insert or update of a document else { // Display the form pnlEdit.Visible = true; // Try to get GroupID if group context exists int currentGroupId = ModuleCommands.CommunityGetCurrentGroupID(); btnDelete.Attributes.Add("style", "display: none;"); btnRefresh.Attributes.Add("style", "display: none;"); // CMSForm initialization formElem.NodeID = Node.NodeID; formElem.SiteName = SiteName; formElem.CultureCode = CultureCode; formElem.ValidationErrorMessage = ValidationErrorMessage; formElem.IsLiveSite = IsLiveSite; // Set group ID if group context exists formElem.GroupID = currentGroupId; // External editing is allowed for live site only if the permissions are checked or user is global administrator or for group context - user is group administrator formElem.AllowExternalEditing = !IsLiveSite || CheckPermissions || MembershipContext.AuthenticatedUser.IsGlobalAdministrator || MembershipContext.AuthenticatedUser.IsGroupAdministrator(currentGroupId); // Set the form mode if (NewDocument) { ci = DataClassInfoProvider.GetDataClassInfo(ClassID); if (ci == null) { throw new Exception(String.Format("[CMSAdminControls/EditForm.aspx]: Class ID '{0}' not found.", ClassID)); } string classDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ci.ClassDisplayName)); titleElem.TitleText = GetString("Content.NewTitle") + ": " + classDisplayName; // Set default template ID formElem.DefaultPageTemplateID = TemplateID > 0 ? TemplateID : ci.ClassDefaultPageTemplateID; // Set document owner formElem.OwnerID = OwnerID; formElem.FormMode = FormModeEnum.Insert; string newClassName = ci.ClassName; string newFormName = newClassName + ".default"; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } if (newFormName.ToLowerCSafe() != formElem.FormName.ToLowerCSafe()) { formElem.FormName = newFormName; } } else if (NewCulture) { formElem.FormMode = FormModeEnum.InsertNewCultureVersion; // Default data document ID formElem.CopyDefaultDataFromDocumentId = CopyDefaultDataFromDocumentID; ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName); formElem.FormName = Node.NodeClassName + ".default"; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } } else { formElem.FormMode = FormModeEnum.Update; ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName); formElem.FormName = String.Empty; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } } // Allow the CMSForm formElem.StopProcessing = false; ReloadForm(); formElem.LoadForm(true); } } } // New culture version else { // Switch to new culture version mode DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion; DocumentManager.NodeID = NodeID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; if (Node != null) { // Offer a new culture creation pnlNewCulture.Visible = true; titleElem.TitleText = GetString("Content.NewCultureVersionTitle") + " (" + HTMLHelper.HTMLEncode(MembershipContext.AuthenticatedUser.PreferredCultureCode) + ")"; lblNewCultureInfo.Text = GetString("ContentNewCultureVersion.Info"); radCopy.Text = GetString("ContentNewCultureVersion.Copy"); radEmpty.Text = GetString("ContentNewCultureVersion.Empty"); radCopy.Attributes.Add("onclick", "ShowSelection();"); radEmpty.Attributes.Add("onclick", "ShowSelection()"); AddScript( "function ShowSelection() { \n" + " if (document.getElementById('" + radCopy.ClientID + "').checked) { document.getElementById('divCultures').style.display = 'block'; } \n" + " else { document.getElementById('divCultures').style.display = 'none'; } \n" + "} \n" ); btnOk.Text = GetString("ContentNewCultureVersion.Create"); // Load culture versions SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID); if (si != null) { lstCultures.Items.Clear(); DataSet nodes = TreeProvider.SelectNodes(si.SiteName, Node.NodeAliasPath, TreeProvider.ALL_CULTURES, false, null, null, null, 1, false); foreach (DataRow nodeCulture in nodes.Tables[0].Rows) { ListItem li = new ListItem(); li.Text = CultureInfoProvider.GetCultureInfo(nodeCulture["DocumentCulture"].ToString()).CultureName; li.Value = nodeCulture["DocumentID"].ToString(); lstCultures.Items.Add(li); } if (lstCultures.Items.Count > 0) { lstCultures.SelectedIndex = 0; } } } else { pnlInfo.Visible = true; lblFormInfo.Text = GetString("EditForm.DocumentNotFound"); } } } // Set flag that the form is loaded mFormLoaded = true; } }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { string preferredCultureCode = LocalizationContext.PreferredCultureCode; InfoDataSet <CultureInfo> siteCultures = CultureSiteInfoProvider.GetSiteCultures(SiteContext.CurrentSiteName); pi = DocumentContext.CurrentPageInfo ?? DocumentContext.CurrentCultureInvariantPageInfo ?? new PageInfo(); // Cultures button MenuItem cultureItem = new MenuItem(); cultureItem.CssClass = "BigButton"; cultureItem.ImageAlign = ImageAlign.Top; cultureItem.ImagePath = URLHelper.UnResolveUrl(UIHelper.GetFlagIconUrl(Page, preferredCultureCode, "16x16"), SystemContext.ApplicationPath); cultureItem.Text = PortalHelper.LocalizeStringForUI("general.cultures"); cultureItem.Tooltip = PortalHelper.LocalizeStringForUI("onsiteedit.languageselector"); cultureItem.ImageAltText = PortalHelper.LocalizeStringForUI("general.cultures"); // Add all cultures to the sub menu foreach (CultureInfo culture in siteCultures) { string iconUrl = UIHelper.GetFlagIconUrl(Page, culture.CultureCode, "16x16"); string cultureName = culture.CultureName; string cultureCode = culture.CultureCode; if (cultureCode != preferredCultureCode) { SubMenuItem menuItem = new SubMenuItem { Text = cultureName, Tooltip = cultureName, ImagePath = iconUrl, ImageAltText = cultureName }; // Build the web part image html bool translationExists = NodeCultures.ContainsKey(cultureCode); if (translationExists) { // Assign click action which changes the document culture menuItem.OnClientClick = "document.location.replace(" + ScriptHelper.GetString(URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, URLHelper.LanguageParameterName, cultureCode)) + ");"; } else { // Display the "Not translated" image menuItem.RightImageIconClass = "icon-ban-sign"; menuItem.RightImageAltText = PortalHelper.LocalizeStringForUI("onsitedit.culturenotavailable"); // Assign click action -> Create new document culture menuItem.OnClientClick = "NewDocumentCulture(" + pi.NodeID + ",'" + cultureCode + "');"; } cultureItem.SubItems.Add(menuItem); } else { // Current culture cultureItem.Text = culture.CultureShortName; cultureItem.Tooltip = cultureName; cultureItem.ImagePath = iconUrl; cultureItem.ImageAltText = cultureName; } } btnCulture.Buttons.Add(cultureItem); }