private string GetTreePath() { // Try get info whether exist linked document in path var documentPathContainsLink = DocumentNodeDataInfoProvider.GetDocumentNodes() .OnSite(SiteContext.CurrentSiteID) .WhereNotNull("NodeLinkedNodeID") .Where(TreePathUtils.GetNodesOnPathWhereCondition(Node.NodeAliasPath, false, false)) .Count > 0; // If node is not link or none of parent documents is not linked document use document name path var treePath = Node.IsLink || documentPathContainsLink ? Node.NodeAliasPath : Node.DocumentNamePath; return(TreePathUtils.GetParentPath($"/{treePath}")); }
protected void Page_Load(object sender, EventArgs e) { // Register the scripts ScriptHelper.RegisterLoader(Page); ScriptHelper.RegisterTooltip(Page); ScriptHelper.RegisterDialogScript(this); if ((SiteContext.CurrentSite != null) && (usrOwner != null)) { usrOwner.SetValue("SiteID", SiteContext.CurrentSite.SiteID); } StringBuilder script = new StringBuilder(); if (Node != null) { // Redirect to information page when no UI elements displayed if (pnlUIOther.IsHidden && pnlUIOwner.IsHidden && pnlUIAlias.IsHidden) { RedirectToUINotAvailable(); } if (Node.IsRoot()) { valAlias.Visible = false; txtAlias.Enabled = false; valAlias.Enabled = false; } else { txtAlias.Enabled = !TreePathUtils.AutomaticallyUpdateDocumentAlias(Node.NodeSiteName); } valAlias.ErrorMessage = GetString("GeneralProperties.RequiresAlias"); txtAlias.MaxLength = TreePathUtils.MaxAliasLength; // Get strings for headings headOtherProperties.Text = GetString("GeneralProperties.OtherGroup"); canEditOwner = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed); ReloadData(); } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ModalDialogsToAdvancedSection", script.ToString(), true); // Reflect processing action pnlContent.Enabled = DocumentManager.AllowSave; }
/// <summary> /// Filters the data to include only documents on given path(s). /// </summary> /// <typeparam name="TQuery">Type of the data query</typeparam> /// <param name="baseQuery">The query being filtered upon</param> /// <param name="paths">List of document paths</param> /// <returns>The filtered query</returns> /// <remarks>DocumentQuery.Path() adds parameters to a property "Paths", but if you are building a where condition that needs to 'OR' the path filter, it won't work since DocumentQuery.Path() doesn't add the path filter into the Where logic until query execution.</remarks> public static TQuery WhereInPath <TQuery>(this WhereConditionBase <TQuery> baseQuery, params string[] paths) where TQuery : WhereConditionBase <TQuery>, new() { var whereCondition = new WhereCondition(); bool combined = paths.Count() > 1; foreach (string current in paths) { whereCondition.Or().Where(new IWhereCondition[] { TreePathUtils.GetAliasPathCondition(current, false, combined) }); } return(baseQuery.Where(whereCondition)); }
/// <summary> /// Returns Correct URL of the 'Set permissions' dialog. /// </summary> private string GetPermissionsDialogUrl(string nodeAliasPath) { string url = ResolveUrl("~/CMSModules/Content/FormControls/Documents/ChangePermissions/ChangePermissions.aspx"); // Use current document path if not set if (string.IsNullOrEmpty(nodeAliasPath) && (DocumentContext.CurrentDocument != null)) { nodeAliasPath = DocumentContext.CurrentDocument.NodeAliasPath; } nodeIdFromPath = TreePathUtils.GetNodeIdByAliasPath(SiteName, MacroResolver.ResolveCurrentPath(nodeAliasPath)); url = URLHelper.AddParameterToUrl(url, "nodeid", nodeIdFromPath.ToString()); url = URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(url)); return(url); }
public async Task <IEnumerable <NavigationItem> > GetSecondaryNavItemsAsync(string StartingPath, PathSelectionEnum PathType = PathSelectionEnum.ChildrenOnly, string[] PageTypes = null, string OrderBy = null, string WhereCondition = null, int MaxLevel = -1, int TopNumber = -1) { List <HierarchyTreeNode> HierarchyNodes = new List <HierarchyTreeNode>(); Dictionary <int, HierarchyTreeNode> NodeIDToHierarchyTreeNode = new Dictionary <int, HierarchyTreeNode>(); List <TreeNode> NewNodeList = new List <TreeNode>(); IEnumerable <TreeNode> Nodes = _GeneralDocumentRepo.GetDocumentsByPath( TreePathUtils.EnsureSingleNodePath(StartingPath), PathType, OrderBy, WhereCondition, MaxLevel, TopNumber, new string[] { nameof(TreeNode.DocumentName), nameof(TreeNode.ClassName), nameof(TreeNode.DocumentCulture), nameof(TreeNode.NodeID), nameof(TreeNode.DocumentID), nameof(TreeNode.DocumentGUID), nameof(TreeNode.NodeParentID), nameof(TreeNode.NodeLevel), nameof(TreeNode.NodeGUID), nameof(TreeNode.NodeAliasPath) }, PageTypes ) .Select(x => (TreeNode)x); // populate ParentNodeIDToTreeNode foreach (TreeNode Node in Nodes) { NodeIDToHierarchyTreeNode.Add(Node.NodeID, new HierarchyTreeNode(Node)); NewNodeList.Add(Node); } // Populate the Children of the TypedResults foreach (TreeNode Node in NewNodeList) { // If no parent exists, add to top level if (!NodeIDToHierarchyTreeNode.ContainsKey(Node.NodeParentID)) { HierarchyNodes.Add(NodeIDToHierarchyTreeNode[Node.NodeID]); } else { // Otherwise, add to the parent element. NodeIDToHierarchyTreeNode[Node.NodeParentID].Children.Add(NodeIDToHierarchyTreeNode[Node.NodeID]); } } // Convert to Model List <NavigationItem> Items = new List <NavigationItem>(); foreach (var HierarchyNavTreeNode in HierarchyNodes) { // Call the check to set the Ancestor is current Items.Add(_helper.GetTreeNodeToNavigationItem(HierarchyNavTreeNode)); } return(Items); }
/// <summary> /// Initialize inner controls /// </summary> /// <param name="path">Node alias path</param> private void InitializeInnerControls(string path) { // Ensure single node path pathElem.Value = TreePathUtils.EnsureSingleNodePath(path); // Only child documents if (path.EndsWithCSafe("/%")) { rbChildren.Checked = true; } else { LoadOtherValues(); } }
/// <summary> /// Filters the data to include only documents on given path. /// </summary> /// <typeparam name="TQuery">Type of the data query</typeparam> /// <param name="condition">The query being filtered upon</param> /// <param name="path">Document path</param> /// <param name="type">Path type to define selection scope</param> /// <returns>The filtered query</returns> /// <remarks> /// DocumentQuery.Path() adds parameters to a property "Paths", but if you are building a where condition that needs to 'OR' the path filter, /// it won't work since DocumentQuery.Path() doesn't add the path filter into the Where logic until query execution. /// </remarks> public static TQuery WhereInPath <TQuery>(this WhereConditionBase <TQuery> condition, string path, PathTypeEnum type = PathTypeEnum.Explicit) where TQuery : WhereConditionBase <TQuery>, new() { var paths = new List <string>(); switch (type) { case PathTypeEnum.Single: { path = SqlHelper.EscapeLikeQueryPatterns(path, true, true, true); paths.Add(path); break; } case PathTypeEnum.Children: { path = SqlHelper.EscapeLikeQueryPatterns(path, true, true, true); paths.Add(TreePathUtils.EnsureChildPath(path)); break; } case PathTypeEnum.Section: { path = SqlHelper.EscapeLikeQueryPatterns(path, true, true, true); paths.Add(TreePathUtils.EnsureChildPath(path)); paths.Add(TreePathUtils.EnsureSinglePath(path)); break; } case PathTypeEnum.Explicit: break; default: break; } bool combined = paths.Count > 1; var customWhereCondition = new WhereCondition(); foreach (string current in paths) { customWhereCondition.Or().Where(new IWhereCondition[] { TreePathUtils.GetAliasPathCondition(current, false, combined) }); } return(condition.Where(customWhereCondition)); }
/// <summary> /// Translates object to new culture. /// </summary> protected void btnTranslate_Click(object sender, EventArgs e) { if (TranslationServiceHelper.IsAuthorizedToTranslateDocument(Node, MembershipContext.AuthenticatedUser)) { try { // Submits the document to translation service string err = translationElem.SubmitToTranslation(); if (string.IsNullOrEmpty(err)) { // Refresh page string script; if (RequiresDialog) { string url = UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(Node) + "?" + URLHelper.LanguageParameterName + "=" + RequiredCulture); script = "window.top.location = " + ScriptHelper.GetString(url) + ";"; } else { ViewModeEnum mode = ViewModeEnum.Edit; if (!TreePathUtils.IsMenuItemType(Node.NodeClassName) && (PortalContext.ViewMode != ViewModeEnum.EditLive)) { mode = ViewModeEnum.EditForm; } script = "if (FramesRefresh) { FramesRefresh(" + Node.NodeID + ", '" + mode + "'); }"; } ScriptHelper.RegisterStartupScript(this, typeof(string), "NewCultureRefreshAction", ScriptHelper.GetScript(script)); } else { ShowError(err); } } catch (Exception ex) { ShowError(GetString("ContentRequest.TranslationFailed"), ex.Message); TranslationServiceHelper.LogEvent(ex); } } else { RedirectToAccessDenied("CMS.Content", "SubmitForTranslation"); } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="sourceName"></param> /// <param name="parameter"></param> object boardSubscriptions_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLower()) { case "displayname": DataRowView dr = (DataRowView)parameter; string url = ResolveUrl(TreePathUtils.GetUrl(ValidationHelper.GetString(dr["NodeAliasPath"], ""), null, mSiteName)); string lang = ValidationHelper.GetString(dr["DocumentCulture"], ""); if (!String.IsNullOrEmpty(lang)) { url += "?" + URLHelper.LanguageParameterName + "=" + lang; } return("<a target=\"_blank\" href=\"" + url + "\">" + HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["BoardDisplayName"], "")) + "</a>"); } return(parameter); }
public void ReloadData(bool force) { if (CopiedNode != null) { if (!RequestHelper.IsPostBack() || force) { // Suggest new document name txtDocumentName.Text = TreePathUtils.GetUniqueDocumentName(CopiedNode.DocumentName, CopiedNode.NodeParentID, 0, CopiedNode.DocumentCulture, CopiedNode.ClassName); plcDocumentName.Visible = true; plcMessage.Visible = false; } } // Set control properties Visible = (CopiedNode != null); txtDocumentName.MaxLength = MaxLength; btnCancel.Text = ResHelper.GetString("general.cancel"); rfvDocumentName.ErrorMessage = ResHelper.GetString("basicform.erroremptyvalue"); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { // WAI validation lblSearch.ResourceString = "ForumSearch.SearchWord"; lblSearch.Attributes.Add("style", "display: none;"); btnGo.Text = GetString("ForumSearch.Go"); if (!String.IsNullOrEmpty(AdvancedSearchPath)) { lnkAdvanceSearch.NavigateUrl = ResolveUrl(TreePathUtils.GetUrl(CMSContext.ResolveCurrentPath(AdvancedSearchPath))); lnkAdvanceSearch.Visible = true; lnkAdvanceSearch.Text = GetString("ForumSearch.AdvanceSearch"); if (!RequestHelper.IsPostBack()) { txtSearch.Text = QueryHelper.GetString("searchtext", txtSearch.Text); } } }
protected object UniGridAlias_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLowerCSafe()) { case "culture": return(UniGridFunctions.CultureDisplayName(parameter)); case "urlpath": { // Parse the URL path string urlPath = ValidationHelper.GetString(parameter, ""); return(TreePathUtils.GetUrlPathDisplayName(urlPath)); } } return(parameter); }
/// <summary> /// Formats path /// </summary> /// <param name="path">Node alias path</param> private string FormatPath(string path) { // Get single node path path = TreePathUtils.EnsureSingleNodePath(path); // Ensure slash at the beginning if (!string.IsNullOrEmpty(path) && !path.StartsWithCSafe("/")) { path = "/" + path; } // Include children if set if (rbChildren.Checked) { path = ((path != null) ? path.TrimEnd('/') : "") + "/%"; } return(path); }
/// <summary> /// Handles the UniGrid's OnExternalDataBound event. /// </summary> private object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLowerCSafe()) { case "documentname": DataRowView dr = (DataRowView)parameter; if (CMSContext.CurrentSite != null) { string url = ResolveUrl(TreePathUtils.GetUrl(ValidationHelper.GetString(dr["NodeAliasPath"], ""), null, mSiteName)); string lang = ValidationHelper.GetString(dr["DocumentCulture"], ""); if (!String.IsNullOrEmpty(lang)) { url += "?" + URLHelper.LanguageParameterName + "=" + lang; } return("<a target=\"_blank\" href=\"" + url + "\">" + HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["DocumentName"], "")) + "</a>"); } else { return(HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["DocumentName"], ""))); } case "approved": return(UniGridFunctions.ColoredSpanYesNo(parameter, true)); case "approve": ImageButton button = ((ImageButton)sender); if (button != null) { bool isApproved = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["SubscriptionApproved"], true); if (isApproved) { button.Visible = false; } } break; } return(parameter); }
private void CheckedChanged() { if (radSelect.Checked) { pnlSelect.Enabled = true; pnlSelect.Visible = true; ctrlProduct.Visible = false; pnlNew.Visible = false; } else { pnlSelect.Enabled = false; pnlSelect.Visible = false; ctrlProduct.Visible = true; pnlNew.Visible = true; // Set mappings TreeNode node = this.Node; if (node != null) { DataClassInfo dci = DataClassInfoProvider.GetDataClass(this.Node.NodeClassName); if (dci != null) { // Get the mapped values ctrlProduct.ProductName = ValidationHelper.GetString(node.GetValue(Convert.ToString(dci.SKUMappings["SKUName"])), ""); ctrlProduct.ProductPrice = ValidationHelper.GetDouble(node.GetValue(Convert.ToString(dci.SKUMappings["SKUPrice"])), 0); ctrlProduct.ProductWeight = ValidationHelper.GetDouble(node.GetValue(Convert.ToString(dci.SKUMappings["SKUWeight"])), 0); ctrlProduct.ProductHeight = ValidationHelper.GetDouble(node.GetValue(Convert.ToString(dci.SKUMappings["SKUHeight"])), 0); ctrlProduct.ProductWidth = ValidationHelper.GetDouble(node.GetValue(Convert.ToString(dci.SKUMappings["SKUWidth"])), 0); ctrlProduct.ProductDepth = ValidationHelper.GetDouble(node.GetValue(Convert.ToString(dci.SKUMappings["SKUDepth"])), 0); ctrlProduct.ProductDescription = ValidationHelper.GetString(node.GetValue(Convert.ToString(dci.SKUMappings["SKUDescription"])), ""); Guid guid = ValidationHelper.GetGuid(node.GetValue(Convert.ToString(dci.SKUMappings["SKUImagePath"])), Guid.Empty); ctrlProduct.ProductImagePath = ((guid != Guid.Empty) ? TreePathUtils.GetAttachmentUrl(guid, this.Node.NodeAlias) : ""); } } // prefill form with values from the document ctrlProduct.SetValues(); } }
protected CMS.DocumentEngine.TreeNode FindProductCategory(string nodeAliasPath) { string path = TreePathUtils.GetSafeNodeAliasPath(nodeAliasPath, CurrentSiteName); var subCategory = TreeHelper.GetDocument(CurrentSiteName, path, Culture, true, "PbcLinear.ProductSubCategory", true, true, CurrentUser); var category = TreeHelper.GetDocument(CurrentSiteName, path, Culture, true, "PbcLinear.ProductCategory", true, true, CurrentUser); var returnedCategory = new CMS.DocumentEngine.TreeNode(); if (subCategory != null) { returnedCategory = subCategory; } if (category != null) { returnedCategory = category; } return(returnedCategory); }
/// <summary> /// Returns link for document view. /// </summary> /// <param name="documentId">Document ID</param> /// <param name="taskTitle">Task title</param> /// <param name="taskType">Type of the task</param> protected string GetDocumentLink(object documentId, object taskTitle, object taskType) { string title = ValidationHelper.GetString(taskTitle, string.Empty); string type = ValidationHelper.GetString(taskType, string.Empty).ToLowerCSafe(); int docId = ValidationHelper.GetInteger(documentId, 0); if ((type != "deletedoc") && (type != "deleteallculutres")) { string viewMode = Convert.ToString((int)ViewModeEnum.LiveSite); // For publish tasks display document in preview mode if ((type == "publishdoc") || (type == "archivedoc")) { viewMode = Convert.ToString((int)ViewModeEnum.Preview); } // Get document url string docUrl = ResolveUrl(TreePathUtils.GetDocumentUrl(docId)) + "?viewmode=" + viewMode; return("<a target=\"_blank\" href=\"" + docUrl + "\">" + HTMLHelper.HTMLEncode(title) + "</a>"); } return(title); }
/// <summary> /// Returns true if document is in specified relationship with with selected document. /// </summary> /// <param name="document">Document to be checked</param> /// <param name="side">Relationship side</param> /// <param name="relationship">Relationship name</param> /// <param name="relatedDocumentPath">Alias path to selected document</param> /// <param name="relatedDocumentSite">Selected document site name</param> public static bool IsInRelationship(object document, string side, string relationship, string relatedDocumentPath, string relatedDocumentSite) { TreeNode doc = document as TreeNode; if (doc != null) { int leftNodeID = 0; int rightNodeID = 0; // Use site of the checked document when no other is specified if (String.IsNullOrEmpty(relatedDocumentSite)) { relatedDocumentSite = doc.NodeSiteName; } // Prepare left and right document for relationship side = side.ToLowerCSafe(); if (side == "left") { leftNodeID = doc.NodeID; rightNodeID = TreePathUtils.GetNodeIdByAliasPath(relatedDocumentSite, relatedDocumentPath); } else if (side == "right") { leftNodeID = TreePathUtils.GetNodeIdByAliasPath(relatedDocumentSite, relatedDocumentPath); rightNodeID = doc.NodeID; } // Get relationship ID from relationship name RelationshipNameInfo relationshipName = RelationshipNameInfoProvider.GetRelationshipNameInfo(relationship); if (relationshipName != null) { // Check whether relationship between the two documents exists return(RelationshipProvider.GetRelationshipInfo(leftNodeID, rightNodeID, relationshipName.RelationshipNameId) != null); } } return(false); }
/// <summary> /// Sets the control with a new URL path /// </summary> /// <param name="urlPath">URL path to set</param> protected void SetURLPath(string urlPath) { radMVC.Checked = false; radRoute.Checked = false; radPage.Checked = false; // Process the URL path if (String.IsNullOrEmpty(urlPath)) { radPage.Checked = true; txtUrlPath.Text = ""; return; } // Parse the path string prefix; Hashtable values = new Hashtable(); TreePathUtils.ParseUrlPath(ref urlPath, out prefix, values); // Examine the prefix if (prefix.StartsWithCSafe(TreePathUtils.URL_PREFIX_MVC, true)) { radMVC.Checked = true; } else if (prefix.StartsWithCSafe(TreePathUtils.URL_PREFIX_ROUTE, true)) { radRoute.Checked = true; } else { radPage.Checked = true; } txtUrlPath.Text = urlPath; txtController.Text = ValidationHelper.GetString(values["controller"], ""); txtAction.Text = ValidationHelper.GetString(values["action"], ""); }
/// <summary> /// Initializes control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { if (string.IsNullOrEmpty(Path)) { Path = DocumentContext.CurrentAliasPath; } Path = TreePathUtils.EnsureSingleNodePath(Path); srcAttach.Path = Path; srcAttach.OrderBy = OrderBy; srcAttach.TopN = SelectTopN; srcAttach.WhereCondition = WhereCondition; srcAttach.SelectedColumns = Columns; srcAttach.FilterName = ValidationHelper.GetString(GetValue("WebPartControlID"), ID); srcAttach.SourceFilterName = FilterName; srcAttach.GetBinary = false; srcAttach.AttachmentGroupGUID = AttachmentGroupGUID; if (string.IsNullOrEmpty(CultureCode)) { srcAttach.CultureCode = DocumentContext.CurrentDocumentCulture.CultureCode; } else { srcAttach.CultureCode = CultureCode; } srcAttach.CombineWithDefaultCulture = CombineWithDefaultCulture; srcAttach.CheckPermissions = CheckPermissions; srcAttach.CacheItemName = CacheItemName; srcAttach.CacheMinutes = CacheMinutes; srcAttach.CacheDependencies = CacheDependencies; srcAttach.LoadPagesIndividually = LoadPagesIndividually; } }
/// <summary> /// Checks whether node with given node ID is contained in a products tree, /// considering the ProductsStartingPath setting. /// </summary> /// <param name="nodeId">NodeID of a node to be checked on.</param> private bool IsAllowedInProductsStartingPath(int nodeId) { var nodePath = TreePathUtils.GetAliasPathByNodeId(nodeId); var nodeSite = TreePathUtils.GetNodeSite(nodeId); if (String.IsNullOrEmpty(nodePath)) { return(false); } if (!String.IsNullOrEmpty(ProductsStartingPath)) { if ((TreePathUtils.GetNodeIdByAliasPath(nodeSite.SiteName, ProductsStartingPath) > 0) && !nodePath.StartsWithCSafe(ProductsStartingPath, true)) { // Products starting path is defined and node on that path exists, // but our node is not contained within that path return(false); } } return(true); }
protected void Page_Load(object sender, EventArgs e) { if (DocumentManager != null) { CMS.DocumentEngine.TreeNode node = DocumentManager.Node; if (node != null) { DocumentSettings = true; // Try get info whether exist linked document in path DataSet ds = DocumentManager.Tree.SelectNodes(CMSContext.CurrentSiteName, "/%", node.DocumentCulture, false, null, "NodeLinkedNodeID IS NOT NULL AND (N'" + SqlHelperClass.GetSafeQueryString(node.NodeAliasPath) + "' LIKE NodeAliasPath + '%')", null, -1, false, 1, "Count(*) AS NumOfDocs"); // If node is not link or none of parent documents is not linked document use document name path if (!node.IsLink && ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NumOfDocs"), 0) == 0) { TreePath = TreePathUtils.GetParentPath("/" + node.DocumentNamePath); } else { // Otherwise use alias path TreePath = TreePathUtils.GetParentPath("/" + node.NodeAliasPath); } } } if (DocumentSettings) { radInheritAll.Text = GetString("InheritLevels.UseTemplateSettigns"); } else { radInheritAll.Text = GetString("InheritLevels.InheritAll"); } radNonInherit.Text = GetString("InheritLevels.NonInherit"); radSelect.Text = GetString("InheritLevels.Select"); radInheritMaster.Text = GetString("InheritLevels.InheritMaster"); }
/// <summary> /// Initialize inner controls /// </summary> /// <param name="path">Node alias path</param> private void InitializeInnerControls(string path) { // Ensure single node path pathElem.Value = TreePathUtils.EnsureSingleNodePath(path); // Only child documents if (path.EndsWithCSafe("/%")) { rbChildren.Checked = true; } else { // Only document if (ValidationHelper.GetBoolean(Form.Data["ScopeExcludeChildren"], false)) { rbDoc.Checked = true; } // Document including children else { rbDocAndChildren.Checked = true; } } }
protected void Page_Load(object sender, EventArgs e) { // Set where condition - show nothing when nodeId is zero UniGridAlias.WhereCondition = "AliasNodeID = " + NodeID; if (Node != null) { // Hide parts which are not relevant to content only nodes if (ShowContentOnlyProperties) { pnlUIPath.Visible = false; pnlUIExtended.Visible = false; pnlUIDocumentAlias.Visible = false; headAlias.Visible = false; } if (Node.NodeAliasPath == "/") { valAlias.Visible = false; } // Check modify permissions if ((MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)) { pnlAlias.Enabled = false; menuElem.Enabled = false; UniGridAlias.GridView.Enabled = false; btnNewAlias.Enabled = false; chkCustomExtensions.Enabled = false; ctrlURL.Enabled = false; } else { ltlScript.Text = ScriptHelper.GetScript("var node = " + NodeID + "; \n var deleteMsg = '" + GetString("DocumentAlias.DeleteMsg") + "';"); UniGridAlias.OnAction += UniGridAlias_OnAction; UniGridAlias.OnExternalDataBound += UniGridAlias_OnExternalDataBound; btnNewAlias.OnClientClick = "window.location.replace('" + UrlResolver.ResolveUrl("Alias_Edit.aspx?nodeid=" + NodeID) + "'); return false;"; } chkCustomExtensions.Text = GetString("GeneralProperties.UseCustomExtensions"); valAlias.ErrorMessage = GetString("GeneralProperties.RequiresAlias"); lblExtensions.Text = GetString("doc.urls.urlextensions") + ResHelper.Colon; txtAlias.MaxLength = TreePathUtils.MaxAliasLength; if (!mIsRoot) { txtAlias.Enabled = !TreePathUtils.AutomaticallyUpdateDocumentAlias(Node.NodeSiteName); } if (!RequestHelper.IsPostBack()) { ReloadData(); } // Get automatic URL path var culture = CultureHelper.GetShortCultureCode(Node.DocumentCulture); ctrlURL.AutomaticURLPath = TreePathUtils.GetUniqueUrlPath(Node, culture); // Reflect processing action pnlPageContent.Enabled = DocumentManager.AllowSave; } }
/// <summary> /// OnExternalDataBound event handler /// </summary> protected object OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLowerCSafe()) { case "aliaspath": return(TreePathUtils.EnsureSingleNodePath((string)parameter)); case "classdisplayname": string docType = ValidationHelper.GetString(parameter, ""); if (docType == "") { return(Control.GetString("general.selectall")); } return(HTMLHelper.HTMLEncode(docType)); case "scopecultureid": int cultureId = ValidationHelper.GetInteger(parameter, 0); if (cultureId > 0) { return(CultureInfoProvider.GetCultureInfo(cultureId).CultureName); } else { return(Control.GetString("general.selectall")); } case "scopeexcluded": { bool allowed = !ValidationHelper.GetBoolean(parameter, false); return(UniGridFunctions.ColoredSpanAllowedExcluded(allowed)); } case "coverage": { DataRowView drv = (DataRowView)parameter; string alias = ValidationHelper.GetString(drv.Row["ScopeStartingPath"], ""); bool children = !ValidationHelper.GetBoolean(drv.Row["ScopeExcludeChildren"], false); // Only child documents if (alias.EndsWithCSafe("/%")) { return(Control.GetString("workflowscope.children")); } else { // Only document if (!children) { return(Control.GetString("workflowscope.doc")); } // Document including children else { return(Control.GetString("workflowscope.docandchildren")); } } } default: return(parameter); } }
/// <summary> /// Yes button click event handler. /// </summary> protected void btnYes_Click(object sender, EventArgs e) { if (IsBannedIP()) { return; } // Prepare the where condition string where = "NodeID = " + NodeID; // Get the documents DataSet ds = null; if (chkAllCultures.Checked) { ds = TreeProvider.SelectNodes(SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, -1, false); } else { ds = TreeProvider.SelectNodes(SiteName, "/%", CultureCode, false, null, where, null, -1, false); } if (!DataHelper.DataSourceIsEmpty(ds)) { // Get node alias string nodeAlias = ValidationHelper.GetString(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeAlias"), string.Empty); // Get parent alias path string parentAliasPath = TreePathUtils.GetParentPath(ValidationHelper.GetString(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeAliasPath"), string.Empty)); string aliasPath = null; string culture = null; string className = null; bool hasUserDeletePermission = false; TreeNode treeNode = null; // Delete the documents foreach (DataRow dr in ds.Tables[0].Rows) { aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], string.Empty); culture = ValidationHelper.GetString(dr["DocumentCulture"], string.Empty); className = ValidationHelper.GetString(dr["ClassName"], string.Empty); // Get the node treeNode = TreeProvider.SelectSingleNode(SiteName, aliasPath, culture, false, className, false); if (treeNode != null) { // Check delete permissions hasUserDeletePermission = !CheckPermissions || IsUserAuthorizedToDeleteDocument(treeNode, chkDestroy.Checked); if (hasUserDeletePermission) { // Delete the document try { LogDeleteActivity(treeNode); DocumentHelper.DeleteDocument(treeNode, TreeProvider, chkAllCultures.Checked, chkDestroy.Checked, true); } catch (Exception ex) { EventLogProvider.LogEvent(EventType.ERROR, "Content", "DELETEDOC", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, MembershipContext.AuthenticatedUser.UserID, MembershipContext.AuthenticatedUser.UserName, treeNode.NodeID, treeNode.GetDocumentName(), RequestContext.UserHostAddress, SiteContext.CurrentSiteID); AddAlert(GetString("ContentRequest.DeleteFailed") + ": " + ex.Message); return; } } // Access denied - not authorized to delete the document else { AddAlert(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), treeNode.NodeAliasPath)); return; } } else { AddAlert(GetString("ContentRequest.ErrorMissingSource")); return; } } RaiseOnAfterDelete(); string rawUrl = RequestContext.RawURL.TrimEnd(new char[] { '/' }); if ((!string.IsNullOrEmpty(nodeAlias)) && (rawUrl.Substring(rawUrl.LastIndexOfCSafe('/')).Contains(nodeAlias))) { // Redirect to the parent url when current url belongs to deleted document URLHelper.Redirect(DocumentURLProvider.GetUrl(parentAliasPath)); } else { // Redirect to current url URLHelper.Redirect(rawUrl); } } else { AddAlert(GetString("DeleteDocument.CultureNotExists")); return; } }
protected void Page_Load(object sender, EventArgs e) { // Register script files ScriptHelper.RegisterCMS(this); ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js"); if (!QueryHelper.ValidateHash("hash")) { pnlContent.Visible = false; ShowError(GetString("dialogs.badhashtext")); return; } // Setup page title text and image PageTitle.TitleText = GetString("Content.TranslateTitle"); EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText); if (IsDialog) { RegisterModalPageScripts(); RegisterEscScript(); plcInfo.Visible = false; pnlButtons.Visible = false; } if (!TranslationServiceHelper.IsTranslationAllowed(CurrentSiteName)) { pnlContent.Visible = false; ShowError(GetString("translations.translationnotallowed")); return; } // Initialize current user currentUser = MembershipContext.AuthenticatedUser; // Initialize events ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished; ctlAsyncLog.OnError += ctlAsyncLog_OnError; ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel; isSelect = QueryHelper.GetBoolean("select", false); if (isSelect) { pnlDocList.Visible = false; pnlDocSelector.Visible = true; translationElem.DisplayMachineServices = false; } var currentCulture = LocalizationContext.CurrentCulture.CultureCode; var displayTargetLanguage = !IsDialog || isSelect; translationElem.DisplayTargetlanguage = displayTargetLanguage; // Get target culture(s) targetCultures = displayTargetLanguage ? translationElem.TargetLanguages : new HashSet <string>(new[] { QueryHelper.GetString("targetculture", currentCulture) }); // Set the target settings var settings = new TranslationSettings(); settings.TargetLanguages.AddRange(targetCultures); var useCurrentAsDefault = QueryHelper.GetBoolean("currentastargetdefault", false); if (!currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(currentCulture, CurrentSiteName)) { // Do not use current culture as default if user has no permissions to edit it useCurrentAsDefault = false; } translationElem.UseCurrentCultureAsDefaultTarget = useCurrentAsDefault; // Do not include default culture if it is current one string defaultCulture = CultureHelper.GetDefaultCultureCode(CurrentSiteName); if (useCurrentAsDefault && !string.Equals(currentCulture, defaultCulture, StringComparison.InvariantCultureIgnoreCase) && !RequestHelper.IsPostBack()) { settings.TargetLanguages.Add(currentCulture); } translationElem.TranslationSettings = settings; allowTranslate = true; if (RequestHelper.IsCallback()) { return; } // If not in select mode, load all the document IDs and check permissions // In select mode, documents are checked when the button is clicked if (!isSelect) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(); // Current Node ID to translate string parentAliasPath = string.Empty; if (Parameters != null) { parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty); nodeIdsArr = ValidationHelper.GetString(Parameters["nodeids"], string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); } if (string.IsNullOrEmpty(parentAliasPath)) { if (nodeIdsArr == null) { // One document translation is requested string nodeIdQuery = QueryHelper.GetString("nodeid", ""); if (nodeIdQuery != "") { // Mode of single node translation pnlList.Visible = false; chkSkipTranslated.Checked = false; translationElem.NodeID = ValidationHelper.GetInteger(nodeIdQuery, 0); nodeIdsArr = new[] { nodeIdQuery }; } else { nodeIdsArr = new string[] { }; } } foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } } else { // Exclude root of the website from multiple translation requested by document listing bulk action var where = new WhereCondition(WhereCondition) .WhereNotEquals("ClassName", SystemDocumentTypes.Root); allDocs = tree.SelectNodes(CurrentSiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%", TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true), "DocumentName", AllLevels ? TreeProvider.ALL_LEVELS : 1, false, 0, DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath"); if (!DataHelper.DataSourceIsEmpty(allDocs)) { foreach (DataTable table in allDocs.Tables) { foreach (DataRow row in table.Rows) { nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0)); } } } } if (nodeIds.Count > 0) { var where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true); DataSet ds = allDocs ?? tree.SelectNodes(CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", TreeProvider.ALL_LEVELS, false); if (!DataHelper.DataSourceIsEmpty(ds)) { string docList = null; cancelNodeId = string.IsNullOrEmpty(parentAliasPath) ? DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID") : TreePathUtils.GetNodeIdByAliasPath(CurrentSiteName, parentAliasPath); 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 += DocumentUIHelper.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 (!TranslationServiceHelper.IsAuthorizedToTranslateDocument(node, currentUser, targetCultures)) { allowTranslate = false; plcMessages.AddError(String.Format(GetString("cmsdesk.notauthorizedtotranslatedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath))); } } } if (!allowTranslate && !RequestHelper.IsPostBack()) { // Hide UI only when security check is performed within first load, if postback used user may loose some setting HideUI(); } } // Display check box for separate submissions for each document if there is more than one document translationElem.DisplaySeparateSubmissionOption = (nodeIds.Count > 1); } else { // Hide everything pnlContent.Visible = false; } } // Register the dialog script ScriptHelper.RegisterDialogScript(this); ctlAsyncLog.TitleText = GetString("contentrequest.starttranslate"); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; }
protected void DocumentManager_OnSaveData(object sender, DocumentManagerEventArgs e) { e.UpdateDocument = false; string errorMessage = null; string newPageName = txtPageName.Text.Trim(); if (!String.IsNullOrEmpty(newPageName)) { // Limit length newPageName = TreePathUtils.EnsureMaxNodeNameLength(newPageName, pageClassName); } TreeNode node = e.Node; node.DocumentName = newPageName; bool updateGuidAfterInsert = false; // Same template for all language versions by default PageTemplateInfo pti = selTemplate.EnsureTemplate(node.DocumentName, node.NodeGUID, ref errorMessage); if (pti != null) { node.SetDefaultPageTemplateID(pti.PageTemplateId); // Template should by updated after document insert if (!pti.IsReusable) { updateGuidAfterInsert = true; } } // Insert node if no error if (String.IsNullOrEmpty(errorMessage)) { // Insert the document // Ensures documents consistency (blog post hierarchy etc.) DocumentManager.EnsureDocumentsConsistency(); DocumentHelper.InsertDocument(node, DocumentManager.ParentNode, DocumentManager.Tree); if (updateGuidAfterInsert) { PageTemplateInfo pageTemplateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(node.NodeTemplateID); if (pageTemplateInfo != null) { // Update template's node GUID pageTemplateInfo.PageTemplateNodeGUID = node.NodeGUID; PageTemplateInfoProvider.SetPageTemplateInfo(pageTemplateInfo); } } // Create default SKU if configured if (ModuleManager.CheckModuleLicense(ModuleName.ECOMMERCE, RequestContext.CurrentDomain, FeatureEnum.Ecommerce, ObjectActionEnum.Insert)) { bool?skuCreated = node.CreateDefaultSKU(); if (skuCreated.HasValue && !skuCreated.Value) { AddError(GetString("com.CreateDefaultSKU.Error")); } } if (node.NodeSKUID > 0) { DocumentManager.UpdateDocument(true); } } else { e.IsValid = false; e.ErrorMessage = errorMessage; } }
/// <summary> /// Initializes control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing ucAttachments.StopProcessing = true; } else { ucAttachments.GetBinary = false; // Basic control properties ucAttachments.HideControlForZeroRows = HideControlForZeroRows; ucAttachments.ZeroRowsText = ZeroRowsText; // Data source properties ucAttachments.WhereCondition = WhereCondition; ucAttachments.OrderBy = OrderBy; ucAttachments.FilterName = FilterName; ucAttachments.CacheItemName = CacheItemName; ucAttachments.CacheDependencies = CacheDependencies; ucAttachments.CacheMinutes = CacheMinutes; ucAttachments.AttachmentGroupGUID = AttachmentGroupGUID; ucAttachments.CheckPermissions = CheckPermissions; ucAttachments.CombineWithDefaultCulture = CombineWithDefaultCulture; if (string.IsNullOrEmpty(CultureCode)) { ucAttachments.CultureCode = DocumentContext.CurrentDocumentCulture.CultureCode; } else { ucAttachments.CultureCode = CultureCode; } ucAttachments.Path = TreePathUtils.EnsureSingleNodePath(MacroResolver.ResolveCurrentPath(Path)); ucAttachments.SiteName = SiteName; ucAttachments.TopN = TopN; #region "Repeater template properties" // Apply transformations if they exist ucAttachments.TransformationName = TransformationName; ucAttachments.AlternatingItemTransformationName = AlternatingItemTransformationName; ucAttachments.FooterTransformationName = FooterTransformationName; ucAttachments.HeaderTransformationName = HeaderTransformationName; ucAttachments.SeparatorTransformationName = SeparatorTransformationName; #endregion // UniPager properties ucAttachments.PageSize = PageSize; ucAttachments.GroupSize = GroupSize; ucAttachments.QueryStringKey = QueryStringKey; ucAttachments.DisplayFirstLastAutomatically = DisplayFirstLastAutomatically; ucAttachments.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically; ucAttachments.HidePagerForSinglePage = HidePagerForSinglePage; switch (PagingMode.ToLowerCSafe()) { case "postback": ucAttachments.PagingMode = UniPagerMode.PostBack; break; default: ucAttachments.PagingMode = UniPagerMode.Querystring; break; } #region "UniPager template properties" // UniPager template properties ucAttachments.PagesTemplate = PagesTemplate; ucAttachments.CurrentPageTemplate = CurrentPageTemplate; ucAttachments.SeparatorTemplate = SeparatorTemplate; ucAttachments.FirstPageTemplate = FirstPageTemplate; ucAttachments.LastPageTemplate = LastPageTemplate; ucAttachments.PreviousPageTemplate = PreviousPageTemplate; ucAttachments.NextPageTemplate = NextPageTemplate; ucAttachments.PreviousGroupTemplate = PreviousGroupTemplate; ucAttachments.NextGroupTemplate = NextGroupTemplate; ucAttachments.LayoutTemplate = LayoutTemplate; #endregion } }
/// <summary> /// UniGrid external data bound. /// </summary> protected object GridDocsOnExternalDataBound(object sender, string sourceName, object parameter) { string attName = null; string attachmentExt = null; DataRowView drv = null; switch (sourceName.ToLowerCSafe()) { case "update": drv = parameter as DataRowView; PlaceHolder plcUpd = new PlaceHolder(); plcUpd.ID = "plcUdateAction"; Panel pnlBlock = new Panel(); pnlBlock.ID = "pnlBlock"; plcUpd.Controls.Add(pnlBlock); // Add disabled image ImageButton imgUpdate = new ImageButton(); imgUpdate.ID = "imgUpdate"; imgUpdate.PreRender += imgUpdate_PreRender; pnlBlock.Controls.Add(imgUpdate); // Add update control // Dynamically load uploader control DirectFileUploader dfuElem = Page.LoadUserControl("~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploader.ascx") as DirectFileUploader; // Set uploader's properties if (dfuElem != null) { dfuElem.ID = "dfuElem" + DocumentID; dfuElem.SourceType = MediaSourceEnum.Attachment; dfuElem.DisplayInline = true; if (!createTempAttachment) { dfuElem.AttachmentGUID = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty); } dfuElem.ForceLoad = true; dfuElem.FormGUID = FormGUID; dfuElem.AttachmentGUIDColumnName = GUIDColumnName; dfuElem.DocumentID = DocumentID; dfuElem.NodeParentNodeID = NodeParentNodeID; dfuElem.NodeClassName = NodeClassName; dfuElem.ResizeToWidth = ResizeToWidth; dfuElem.ResizeToHeight = ResizeToHeight; dfuElem.ResizeToMaxSideSize = ResizeToMaxSideSize; dfuElem.AllowedExtensions = AllowedExtensions; dfuElem.ImageUrl = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload.png")); dfuElem.ImageHeight = 16; dfuElem.ImageWidth = 16; dfuElem.InsertMode = false; dfuElem.ParentElemID = ClientID; dfuElem.IncludeNewItemInfo = true; dfuElem.CheckPermissions = CheckPermissions; dfuElem.NodeSiteName = SiteName; dfuElem.IsLiveSite = IsLiveSite; // Setting of the direct single mode dfuElem.UploadMode = MultifileUploaderModeEnum.DirectSingle; dfuElem.Width = 16; dfuElem.Height = 16; dfuElem.MaxNumberToUpload = 1; dfuElem.PreRender += dfuElem_PreRender; pnlBlock.Controls.Add(dfuElem); } attName = ValidationHelper.GetString(drv["AttachmentName"], string.Empty); attachmentExt = ValidationHelper.GetString(drv["AttachmentExtension"], string.Empty); int nodeGroupId = (Node != null) ? Node.GetIntegerValue("NodeGroupID") : 0; bool displayGroupAdmin = true; // Check group admin for live site if (IsLiveSite && (nodeGroupId > 0)) { displayGroupAdmin = CMSContext.CurrentUser.IsGroupAdministrator(nodeGroupId); } // Check if WebDAV allowed by the form bool allowWebDAV = (Form == null) ? true : Form.AllowWebDAV; // Add WebDAV edit control if (allowWebDAV && CMSContext.IsWebDAVEnabled(SiteName) && RequestHelper.IsWindowsAuthentication() && (FormGUID == Guid.Empty) && WebDAVSettings.IsExtensionAllowedForEditMode(attachmentExt, SiteName) && displayGroupAdmin) { // Dynamically load control WebDAVEditControl webdavElem = Page.LoadUserControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl; // Set editor's properties if (webdavElem != null) { webdavElem.ID = "webdavElem" + DocumentID; // Ensure form identification if ((Form != null) && (Form.Parent != null)) { webdavElem.FormID = Form.Parent.ClientID; } webdavElem.PreRender += webdavElem_PreRender; webdavElem.SiteName = SiteName; webdavElem.FileName = attName; webdavElem.NodeAliasPath = Node.NodeAliasPath; webdavElem.NodeCultureCode = Node.DocumentCulture; if (FieldInfo != null) { webdavElem.AttachmentFieldName = FieldInfo.Name; } // Set Group ID for live site webdavElem.GroupID = IsLiveSite ? nodeGroupId : 0; webdavElem.IsLiveSite = IsLiveSite; // Align left if WebDAV is enabled and windows authentication is enabled bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL()); pnlBlock.Style.Add("text-align", isRTL ? "right" : "left"); pnlBlock.Controls.Add(webdavElem); } } return(plcUpd); case "edit": // Get file extension string extension = ValidationHelper.GetString(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentExtension"], string.Empty).ToLowerCSafe(); // Get attachment GUID attachmentGuid = ValidationHelper.GetGuid(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentGUID"], Guid.Empty); if (sender is ImageButton) { ImageButton img = (ImageButton)sender; if (createTempAttachment) { img.Visible = false; } else { img.AlternateText = extension; img.ToolTip = attachmentGuid.ToString(); img.PreRender += img_PreRender; } } break; case "delete": if (sender is ImageButton) { ImageButton imgDelete = (ImageButton)sender; // Turn off validation imgDelete.CausesValidation = false; imgDelete.PreRender += imgDelete_PreRender; // Explicitly initialize confirmation imgDelete.OnClientClick = "if(DeleteConfirmation() == false){return false;}"; } break; case "attachmentname": { drv = parameter as DataRowView; // Get attachment GUID attachmentGuid = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty); // Get attachment extension attachmentExt = ValidationHelper.GetString(drv["AttachmentExtension"], string.Empty); bool isImage = ImageHelper.IsImage(attachmentExt); string iconUrl = GetFileIconUrl(attachmentExt, "List"); // Get link for attachment string attachmentUrl = null; attName = ValidationHelper.GetString(drv["AttachmentName"], string.Empty); int documentId = DocumentID; if (Node != null) { if (IsLiveSite && (documentId > 0)) { attachmentUrl = CMSContext.ResolveUIUrl(TreePathUtils.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, CMSContext.CurrentSiteName), 0, null)); } else { attachmentUrl = CMSContext.ResolveUIUrl(TreePathUtils.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, CMSContext.CurrentSiteName), VersionHistoryID, null)); } } else { attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attachmentGuid, VersionHistoryID)); } attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString()); // Ensure correct URL if (OriginalNodeSiteName != CMSContext.CurrentSiteName) { attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "sitename", OriginalNodeSiteName); } // Add latest version requirement for live site if (IsLiveSite && (documentId > 0)) { // Add requirement for latest version of files for current document string newparams = "latestfordocid=" + documentId; newparams += "&hash=" + ValidationHelper.GetHashString("d" + documentId); attachmentUrl += "&" + newparams; } // Optionally trim attachment name string attachmentName = TextHelper.LimitLength(attName, ATTACHMENT_NAME_LIMIT, "..."); // Tooltip string tooltip = null; if (ShowTooltip) { string title = ValidationHelper.GetString(drv["AttachmentTitle"], string.Empty); ; string description = ValidationHelper.GetString(drv["AttachmentDescription"], string.Empty); int imageWidth = ValidationHelper.GetInteger(drv["AttachmentImageWidth"], 0); int imageHeight = ValidationHelper.GetInteger(drv["AttachmentImageHeight"], 0); tooltip = UIHelper.GetTooltipAttributes(attachmentUrl, imageWidth, imageHeight, title, attachmentName, attachmentExt, description, null, 300); } // Icon string imageTag = "<img class=\"Icon\" src=\"" + iconUrl + "\" alt=\"" + attachmentName + "\" />"; if (isImage) { return("<a href=\"#\" onclick=\"javascript: window.open('" + attachmentUrl + "'); return false;\"><span " + tooltip + ">" + imageTag + attachmentName + "</span></a>"); } else { return("<a href=\"" + attachmentUrl + "\"><span id=\"" + attachmentGuid + "\" " + tooltip + ">" + imageTag + attachmentName + "</span></a>"); } } case "attachmentsize": long size = ValidationHelper.GetLong(parameter, 0); return(DataHelper.GetSizeString(size)); } return(parameter); }