protected void Page_Load(object sender, EventArgs e)
    {
        string commMenuID = "commMenu_" + ClientID;

        cmcApp.Parameter   = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.APPROVE);
        cmcApp.MenuID      = commMenuID;
        cmcRej.Parameter   = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.REJECT);
        cmcRej.MenuID      = commMenuID;
        cmcCheck.Parameter = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.CHECKIN);
        cmcCheck.MenuID    = commMenuID;
        cmcArch.Parameter  = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.ARCHIVE);
        cmcArch.MenuID     = commMenuID;

        libraryMenuElem.LoadingContent = menuComm.LoadingContent = new ContextMenuItem {
            ResourceString = "ContextMenu.Loading"
        }.GetRenderedHTML();
        menuComm.OnReloadData += menuComm_OnReloadData;
        menuComm.MenuID        = commMenuID;

        // Initialize menu element
        libraryMenuElem.OnReloadData += libraryMenuElem_OnReloadData;

        libraryMenuElem.MenuID                     = "libraryMenu_" + ClientID;
        libraryMenuElem.MouseButton                = MouseButton;
        libraryMenuElem.OffsetX                    = OffsetX;
        libraryMenuElem.OffsetY                    = OffsetY;
        libraryMenuElem.VerticalPosition           = VerticalPosition;
        libraryMenuElem.HorizontalPosition         = HorizontalPosition;
        libraryMenuElem.ActiveItemCssClass         = ActiveItemCssClass;
        libraryMenuElem.ActiveItemOffset           = ActiveItemOffset;
        libraryMenuElem.ActiveItemInactiveCssClass = ActiveItemInactiveCssClass;

        ExternalEditHelper.RenderScripts(this);
    }
    private void CreateExternalEditControl(DataRowView drv, Panel pnlBlock)
    {
        // Check if external edit allowed by the form
        bool allowExt = (Form == null) || Form.AllowExternalEditing;

        if (allowExt && (FormGUID == Guid.Empty))
        {
            var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.Attachment, SiteName, new DataRowContainer(drv), IsLiveSite, Node);
            if (ctrl != null)
            {
                ctrl.Enabled = Enabled;
                ctrl.ID      = "extEdit" + DocumentID;

                // Ensure form identification
                if ((Form != null) && (Form.Parent != null))
                {
                    ctrl.FormID = Form.Parent.ClientID;
                }
                ctrl.SiteName = SiteName;

                ctrl.PreRender += extEdit_PreRender;

                if (FieldInfo != null)
                {
                    ctrl.AttachmentFieldName = FieldInfo.Name;
                }

                // Adjust styles
                bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());

                pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");
                mUpdateIconPanelWidth = 32;
            }
        }
    }
Exemplo n.º 3
0
    private void CreateExternalEditControl(DataRowView drv, Panel pnlBlock)
    {
        int  nodeGroupId       = ((Node != null) && (Node.DocumentID > 0)) ? Node.GetValue("NodeGroupID", 0) : 0;
        bool displayGroupAdmin = true;

        // Check group admin for live site
        if (IsLiveSite && (nodeGroupId > 0))
        {
            displayGroupAdmin = MembershipContext.AuthenticatedUser.IsGroupAdministrator(nodeGroupId);
        }

        // Check if external editing allowed by the form
        bool allowExt = (Form == null) || Form.AllowExternalEditing;

        if (allowExt && (FormGUID == Guid.Empty) && displayGroupAdmin)
        {
            var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.Attachment, SiteName, new DataRowContainer(drv), IsLiveSite, Node);
            if (ctrl != null)
            {
                ctrl.ID = "extEdit" + DocumentID;

                // Ensure form identification
                if (Form?.Parent != null)
                {
                    ctrl.FormID = Form.Parent.ClientID;
                }
                ctrl.SiteName = SiteName;

                if (FieldInfo != null)
                {
                    ctrl.AttachmentFieldName = FieldInfo.Name;
                }

                ctrl.PreRender += extEdit_PreRender;

                // Adjust the styles
                bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());
                pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");
            }
        }
    }
    protected object gridFiles_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        GridViewRow gvr;
        DataRowView drv;
        string      fileGuid;

        switch (sourceName.ToLowerCSafe())
        {
        case "edit":

            var btnImageEditor = (CMSGridActionButton)sender;
            gvr = (GridViewRow)parameter;
            drv = (DataRowView)gvr.DataItem;

            fileGuid = ValidationHelper.GetString(drv["MetaFileGUID"], String.Empty);
            string fileExtension = ValidationHelper.GetString(drv["MetaFileExtension"], String.Empty);

            // Initialize properties
            btnImageEditor.Visible = true;

            // Display button only if 'Modify' is allowed
            if (AllowModify)
            {
                string query = String.Format("?metafileguid={0}&clientid={1}", fileGuid, ClientID);
                query = URLHelper.AddUrlParameter(query, "hash", QueryHelper.GetHash(query));

                // Display button only if metafile is in supported image format
                if (ImageHelper.IsSupportedByImageEditor(fileExtension))
                {
                    // Initialize button with script
                    btnImageEditor.OnClientClick = String.Format("OpenImageEditor({0}); return false;", ScriptHelper.GetString(query));
                }
                // Non-image metafile
                else
                {
                    // Initialize button with script
                    btnImageEditor.OnClientClick = String.Format("OpenEditor({0}); return false;", ScriptHelper.GetString(query));
                }
            }
            else
            {
                btnImageEditor.Enabled = false;
            }

            break;

        case "paste":

            var btnPaste = (CMSGridActionButton)sender;
            gvr = (GridViewRow)parameter;
            drv = (DataRowView)gvr.DataItem;

            fileGuid = ValidationHelper.GetString(drv["MetaFileGUID"], String.Empty);
            int fileWidth  = ValidationHelper.GetInteger(drv["MetaFileImageWidth"], 0);
            int fileHeight = ValidationHelper.GetInteger(drv["MetaFileImageHeight"], 0);

            if (AllowPasteAttachments)
            {
                if ((fileWidth > 0) && (fileHeight > 0))
                {
                    string appPath = SystemContext.ApplicationPath;
                    if ((appPath == null) || (appPath == "/"))
                    {
                        appPath = String.Empty;
                    }
                    btnPaste.OnClientClick = String.Format("PasteImage('{0}/CMSPages/GetMetaFile.aspx?fileguid={1}'); return false", UseVirtualPathOnPaste ? "~" : appPath, fileGuid);
                }
                else
                {
                    btnPaste.Enabled = false;
                }
            }
            else
            {
                btnPaste.Visible = false;
            }

            break;

        case "delete":
            if (!AllowModify)
            {
                var btnDelete = (CMSGridActionButton)sender;
                btnDelete.Enabled = false;
            }

            break;

        case "#objectmenu":
            if (HideObjectMenu)
            {
                ((CMSGridActionButton)sender).Visible = false;
            }
            break;

        case "name":
            drv = (DataRowView)parameter;

            string fileName = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileName"), string.Empty);
            fileGuid = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileGUID"), string.Empty);
            string fileExt = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileExtension"), string.Empty);

            bool   isImage = ImageHelper.IsImage(fileExt);
            string fileUrl = String.Format("{0}?fileguid={1}&chset={2}", URLHelper.GetAbsoluteUrl("~/CMSPages/GetMetaFile.aspx"), fileGuid, Guid.NewGuid());

            // Tooltip
            string title       = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileTitle"), string.Empty);
            string description = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileDescription"), string.Empty);
            int    imageWidth  = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageWidth"), 0);
            int    imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageHeight"), 0);
            string tooltip     = UIHelper.GetTooltipAttributes(fileUrl, imageWidth, imageHeight, title, fileName, fileExt, description, null, 300);

            // Icon
            string iconTag = UIHelper.GetFileIcon(Page, fileExt, tooltip: fileName);
            if (isImage)
            {
                return(String.Format("<a href=\"#\" onclick=\"javascript: window.open('{0}'); return false;\" class=\"cms-icon-link\"><span id=\"{1}\" {2}>{3}{4}</span></a>", fileUrl, fileGuid, tooltip, iconTag, fileName));
            }
            else
            {
                fileUrl = URLHelper.AddParameterToUrl(fileUrl, "disposition", "attachment");

                // NOTE: OnClick here is needed to avoid loader to show because even for download links, the pageUnload event is fired
                return(String.Format("<a href=\"{0}\" onclick=\"javascript: {5}\" class=\"cms-icon-link\"><span id=\"{1}\" {2}>{3}{4}</span></a>", fileUrl, fileGuid, tooltip, iconTag, fileName, ScriptHelper.GetDisableProgressScript()));
            }

        case "size":
            return(DataHelper.GetSizeString(ValidationHelper.GetLong(parameter, 0)));

        case "update":
        {
            drv = (DataRowView)parameter;
            Panel pnlBlock = new Panel
            {
                ID = "pnlBlock"
            };

            string siteName = null;

            if (SiteID > 0)
            {
                SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteID);
                if (si != null)
                {
                    siteName = si.SiteName;
                }
            }
            else
            {
                siteName = SiteContext.CurrentSiteName;
            }

            // Add update control
            // Dynamically load uploader control
            var dfuElem = Page.LoadUserControl("~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploader.ascx") as DirectFileUploader;
            if (dfuElem != null)
            {
                dfuElem.ID                 = "dfuElem" + ObjectID;
                dfuElem.SourceType         = MediaSourceEnum.MetaFile;
                dfuElem.ControlGroup       = "Uploader_" + ObjectID;
                dfuElem.DisplayInline      = true;
                dfuElem.ForceLoad          = true;
                dfuElem.MetaFileID         = ValidationHelper.GetInteger(drv["MetaFileID"], 0);
                dfuElem.ObjectID           = ObjectID;
                dfuElem.ObjectType         = ObjectType;
                dfuElem.Category           = Category;
                dfuElem.ParentElemID       = ClientID;
                dfuElem.ShowIconMode       = true;
                dfuElem.InsertMode         = false;
                dfuElem.ParentElemID       = ClientID;
                dfuElem.IncludeNewItemInfo = true;
                dfuElem.SiteID             = SiteID;
                dfuElem.IsLiveSite         = IsLiveSite;

                // Setting of the direct single mode
                dfuElem.UploadMode        = MultifileUploaderModeEnum.DirectSingle;
                dfuElem.Width             = 16;
                dfuElem.Height            = 16;
                dfuElem.MaxNumberToUpload = 1;

                if (AllowedExtensions != null)
                {
                    dfuElem.AllowedExtensions = AllowedExtensions;
                }

                pnlBlock.Controls.Add(dfuElem);
            }

            // Setup external edit
            var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.MetaFile, siteName, new DataRowContainer(drv), IsLiveSite);
            if (ctrl != null)
            {
                ctrl.Enabled = AllowModify;
            }

            return(pnlBlock);
        }
        }

        return(parameter);
    }
    protected void libraryMenuElem_OnReloadData(object sender, EventArgs e)
    {
        var parameters = (libraryMenuElem.Parameter ?? string.Empty).Split(new [] { '|' }, StringSplitOptions.RemoveEmptyEntries);

        if (parameters.Length == 2)
        {
            // Parse identifier and document culture from library parameter
            int    nodeId      = ValidationHelper.GetInteger(parameters[0], 0);
            string cultureCode = ValidationHelper.GetString(parameters[1], string.Empty);

            DocumentManager.Mode = FormModeEnum.Update;
            DocumentManager.ClearNode();
            DocumentManager.DocumentID  = 0;
            DocumentManager.NodeID      = nodeId;
            DocumentManager.CultureCode = cultureCode;

            TreeNode node = DocumentManager.Node;

            bool contextMenuVisible    = false;
            bool localizeVisible       = false;
            bool editVisible           = false;
            bool uploadVisible         = false;
            bool copyVisible           = false;
            bool deleteVisible         = false;
            bool openVisible           = false;
            bool propertiesVisible     = false;
            bool permissionsVisible    = false;
            bool versionHistoryVisible = false;

            bool checkOutVisible         = false;
            bool checkInVisible          = false;
            bool undoCheckoutVisible     = false;
            bool submitToApprovalVisible = false;
            bool rejectVisible           = false;
            bool archiveVisible          = false;

            if ((node != null) && (!CheckPermissions || (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed)))
            {
                // Get original node (in case of linked documents)
                TreeNode originalNode = TreeProvider.GetOriginalNode(node);

                string siteName = SiteContext.CurrentSiteName;
                string currentDocumentCulture = DocumentContext.CurrentDocumentCulture.CultureCode;

                if (SiteContext.CurrentSiteID != originalNode.NodeSiteID)
                {
                    SiteInfo si = SiteInfoProvider.GetSiteInfo(originalNode.NodeSiteID);
                    siteName = si.SiteName;
                }

                if (!DocumentManager.ProcessingAction)
                {
                    // Get permissions
                    const bool authorizedToRead              = true;
                    bool       authorizedToDelete            = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Delete) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToModify            = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed);
                    bool       authorizedCultureToModify     = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify, false) == AuthorizationResultEnum.Allowed) && TreeSecurityProvider.HasUserCultureAllowed(NodePermissionsEnum.Modify, currentDocumentCulture, MembershipContext.AuthenticatedUser, siteName);
                    bool       authorizedToModifyPermissions = (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToCreate            = MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(node.NodeParentID, node.NodeClassName);

                    // Hide menu when user has no 'Read' permissions on document
                    libraryMenuElem.Visible = authorizedToRead;

                    // First evaluation of control's visibility
                    bool differentCulture = (CMSString.Compare(node.DocumentCulture, currentDocumentCulture, true) != 0);

                    localizeVisible       = differentCulture && authorizedToCreate && authorizedCultureToModify;
                    uploadVisible         = authorizedToModify && DocumentManager.AllowSave;
                    copyVisible           = authorizedToCreate && authorizedToModify;
                    deleteVisible         = authorizedToDelete;
                    openVisible           = authorizedToRead;
                    propertiesVisible     = authorizedToModify;
                    permissionsVisible    = authorizedToModifyPermissions;
                    versionHistoryVisible = authorizedToModify;

                    editVisible = authorizedToModify;

                    // Get next step info
                    var stps     = new List <WorkflowStepInfo>();
                    var workflow = DocumentManager.Workflow;

                    bool basicWorkflow = true;
                    if (workflow != null)
                    {
                        basicWorkflow = workflow.IsBasic;
                        stps          = WorkflowManager.GetNextStepInfo(node);
                    }
                    var appSteps  = stps.FindAll(s => !s.StepIsArchived);
                    var archSteps = stps.FindAll(s => s.StepIsArchived);

                    // Workflow actions
                    submitToApprovalVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.APPROVE) && (appSteps.Count > 0);
                    rejectVisible           = DocumentManager.IsActionAllowed(DocumentComponentEvents.REJECT);
                    archiveVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.ARCHIVE) && ((archSteps.Count > 0) || basicWorkflow);
                    checkOutVisible         = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKOUT);
                    checkInVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKIN);
                    undoCheckoutVisible     = DocumentManager.IsActionAllowed(DocumentComponentEvents.UNDO_CHECKOUT);

                    string parameterScript = "GetContextMenuParameter('" + libraryMenuElem.MenuID + "')";

                    // Initialize edit menu item
                    Guid attachmentGuid = ValidationHelper.GetGuid(node.GetValue("FileAttachment"), Guid.Empty);

                    // If attachment field doesn't allow empty value and the value is empty
                    if ((FieldInfo != null) && !FieldInfo.AllowEmpty && (attachmentGuid == Guid.Empty))
                    {
                        submitToApprovalVisible = false;
                        archiveVisible          = false;
                        checkInVisible          = false;
                    }

                    // Get attachment
                    var ai = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, siteName, false);

                    Panel currentPanel = pnlEdit;

                    if (editVisible)
                    {
                        if (ai != null)
                        {
                            // Setup external editing
                            var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlEditPadding, FileTypeEnum.Attachment, null, ai, IsLiveSite, node);
                            if (ctrl != null)
                            {
                                ctrl.ID = "editAttachment";

                                ctrl.AttachmentFieldName = "FileAttachment";

                                ctrl.LabelText = GetString("general.edit");

                                ctrl.RefreshScript = JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'ExternalRefresh');";

                                ctrl.ReloadData(true);

                                pnlEditPadding.CssClass = ctrl.EnabledResult ? "ItemPadding" : "ItemPaddingDisabled";
                            }
                            else
                            {
                                pnlEditPadding.Visible = false;
                            }
                        }
                        else
                        {
                            editVisible = false;
                            openVisible = false;
                        }
                    }

                    Panel previousPanel = currentPanel;
                    currentPanel = pnlUpload;

                    // Initialize upload menu item
                    if (authorizedToModify)
                    {
                        // Initialize direct file uploader
                        updateAttachment.Text = GetString("general.update");
                        updateAttachment.InnerElementClass        = "LibraryContextUploader";
                        updateAttachment.DocumentID               = node.DocumentID;
                        updateAttachment.ParentElemID             = ClientID;
                        updateAttachment.SourceType               = MediaSourceEnum.Attachment;
                        updateAttachment.AttachmentGUIDColumnName = "FileAttachment";
                        updateAttachment.IsLiveSite               = IsLiveSite;

                        // Set allowed extensions
                        if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom")
                        {
                            // Load allowed extensions
                            updateAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], "");
                        }
                        else
                        {
                            // Use site settings
                            updateAttachment.AllowedExtensions = SettingsKeyInfoProvider.GetStringValue(siteName + ".CMSUploadExtensions");
                        }

                        updateAttachment.ReloadData();
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlLocalize;

                    // Initialize localize menu item
                    if (localizeVisible)
                    {
                        lblLocalize.RefreshText();
                        pnlLocalize.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Localize');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlCopy;

                    // Initialize copy menu item
                    if (copyVisible)
                    {
                        lblCopy.RefreshText();
                        pnlCopy.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ",'Copy');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlDelete;

                    // Initialize delete menu item
                    if (deleteVisible)
                    {
                        lblDelete.RefreshText();
                        pnlDelete.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Delete');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlOpen;

                    // Initialize open menu item
                    if (openVisible)
                    {
                        lblOpen.RefreshText();
                        if (ai != null)
                        {
                            // Get document URL
                            string attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(node.NodeGUID, node.NodeAlias));
                            if (authorizedToModify)
                            {
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(node.DocumentID, string.Empty));
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + node.DocumentID));
                            }
                            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                            if (!string.IsNullOrEmpty(attachmentUrl))
                            {
                                pnlOpen.Attributes.Add("onclick", "location.href = " + ScriptHelper.GetString(attachmentUrl) + ";");
                            }
                        }
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlProperties;

                    // Initialize properties menu item
                    lblProperties.RefreshText();
                    pnlProperties.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Properties');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlPermissions;

                    // Initialize permissions menu item
                    lblPermissions.RefreshText();
                    pnlPermissions.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Permissions');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlVersionHistory;

                    // Initialize version history menu item
                    lblVersionHistory.RefreshText();
                    pnlVersionHistory.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'VersionHistory');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = null;
                    currentPanel  = pnlCheckOut;

                    // Initialize checkout menu item
                    if (checkOutVisible)
                    {
                        lblCheckOut.RefreshText();
                        pnlCheckOut.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckOut');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlCheckIn;

                    // Initialize check in menu item
                    if (checkInVisible)
                    {
                        lblCheckIn.RefreshText();
                        pnlCheckIn.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckIn');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlUndoCheckout;

                    // Initialize undo checkout menu item
                    if (undoCheckoutVisible)
                    {
                        lblUndoCheckout.RefreshText();
                        pnlUndoCheckout.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'UndoCheckout');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlSubmitToApproval;

                    // Initialize submit to approval / publish menu item
                    if (submitToApprovalVisible)
                    {
                        // Only one next step
                        if (appSteps.Count == 1)
                        {
                            if (appSteps[0].StepIsPublished)
                            {
                                // Set 'Publish' label
                                lblSubmitToApproval.ResourceString = "general.publish";
                                cmcApp.Parameter = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.PUBLISH);
                            }
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'SubmitToApproval');");
                        }
                        // Multiple steps - display dialog
                        else
                        {
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new [] { "'" + DocumentComponentEvents.APPROVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcApp.Enabled = false;
                        }

                        lblSubmitToApproval.RefreshText();
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlReject;

                    // Initialize reject menu item
                    if (rejectVisible)
                    {
                        lblReject.RefreshText();
                        pnlReject.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Reject');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlArchive;

                    // Initialize archive menu item
                    if (archiveVisible)
                    {
                        // Only one archive step
                        if ((archSteps.Count == 1) || basicWorkflow)
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Archive');");
                        }
                        // Multiple archive steps - display dialog
                        else
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new [] { "'" + DocumentComponentEvents.ARCHIVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcArch.Enabled = false;
                        }

                        lblArchive.RefreshText();
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    // Set up visibility of menu items
                    pnlLocalize.Visible       = localizeVisible;
                    pnlUpload.Visible         = uploadVisible;
                    pnlDelete.Visible         = deleteVisible;
                    pnlCopy.Visible           = copyVisible;
                    pnlOpen.Visible           = openVisible;
                    pnlProperties.Visible     = propertiesVisible;
                    pnlPermissions.Visible    = permissionsVisible;
                    pnlVersionHistory.Visible = versionHistoryVisible;
                    pnlEdit.Visible           = editVisible;

                    pnlCheckOut.Visible         = checkOutVisible;
                    pnlCheckIn.Visible          = checkInVisible;
                    pnlUndoCheckout.Visible     = undoCheckoutVisible;
                    pnlSubmitToApproval.Visible = submitToApprovalVisible;
                    pnlReject.Visible           = rejectVisible;
                    pnlArchive.Visible          = archiveVisible;

                    // Set up visibility of whole menu
                    contextMenuVisible = true;
                }

                if (DocumentManager.ProcessingAction)
                {
                    // Setup 'No action available' menu item
                    pnlNoAction.Visible        = true;
                    lblNoAction.ResourceString = null;
                    lblNoAction.Text           = DocumentManager.GetDocumentInfo(true);
                    lblNoAction.RefreshText();
                }
                else
                {
                    // Set up visibility of separators
                    bool firstGroupVisible  = editVisible || uploadVisible || localizeVisible;
                    bool secondGroupVisible = copyVisible || deleteVisible || openVisible;
                    bool thirdGroupVisible  = propertiesVisible || permissionsVisible || versionHistoryVisible;
                    bool fourthGroupVisible = checkOutVisible || checkInVisible || undoCheckoutVisible || submitToApprovalVisible || rejectVisible || archiveVisible;

                    pnlSep1.Visible = firstGroupVisible && secondGroupVisible;
                    pnlSep2.Visible = secondGroupVisible && thirdGroupVisible;
                    pnlSep3.Visible = thirdGroupVisible && fourthGroupVisible;

                    // Setup 'No action available' menu item
                    pnlNoAction.Visible = !contextMenuVisible;
                    lblNoAction.RefreshText();
                }
            }
        }
    }
Exemplo n.º 6
0
    /// <summary>
    /// UniGrid external data bound.
    /// </summary>
    protected object GridDocsOnExternalDataBound(object sender, string sourceName, object parameter)
    {
        string      attName;
        string      attachmentExt;
        DataRowView drv;

        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 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.ShowIconMode        = true;
                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.MaxNumberToUpload = 1;

                dfuElem.PreRender += dfuElem_PreRender;
                pnlBlock.Controls.Add(dfuElem);
            }

            int  nodeGroupId       = ((Node != null) && (Node.DocumentID > 0)) ? Node.GetValue("NodeGroupID", 0) : 0;
            bool displayGroupAdmin = true;

            // Check group admin for live site
            if (IsLiveSite && (nodeGroupId > 0))
            {
                displayGroupAdmin = MembershipContext.AuthenticatedUser.IsGroupAdministrator(nodeGroupId);
            }

            // Check if external editing allowed by the form
            bool allowExt = (Form == null) || Form.AllowExternalEditing;

            if (allowExt && (FormGUID == Guid.Empty) && displayGroupAdmin)
            {
                var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.Attachment, SiteName, new DataRowContainer(drv), IsLiveSite, Node);
                if (ctrl != null)
                {
                    ctrl.ID = "extEdit" + DocumentID;

                    // Ensure form identification
                    if ((Form != null) && (Form.Parent != null))
                    {
                        ctrl.FormID = Form.Parent.ClientID;
                    }
                    ctrl.SiteName = SiteName;

                    if (FieldInfo != null)
                    {
                        ctrl.AttachmentFieldName = FieldInfo.Name;
                    }

                    ctrl.PreRender += extEdit_PreRender;

                    // Adjust the styles
                    bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());
                    pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");
                }
            }

            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 CMSGridActionButton)
            {
                CMSGridActionButton img = (CMSGridActionButton)sender;
                if (createTempAttachment)
                {
                    img.Visible = false;
                }
                else
                {
                    img.ScreenReaderDescription = extension;
                    img.ToolTip    = attachmentGuid.ToString();
                    img.PreRender += img_PreRender;
                }
            }
        }
        break;

        case "delete":
            if (sender is CMSGridActionButton)
            {
                CMSGridActionButton imgDelete = (CMSGridActionButton)sender;
                // Turn off validation
                imgDelete.CausesValidation = false;
                imgDelete.PreRender       += imgDelete_PreRender;
            }
            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);
            bool isTemp  = ValidationHelper.GetGuid(drv["AttachmentFormGUID"], Guid.Empty) != Guid.Empty;

            // Get link for attachment
            string attachmentUrl = null;
            attName = ValidationHelper.GetString(drv["AttachmentName"], string.Empty);
            int documentId = DocumentID;

            if (documentId > 0)
            {
                int versionHistoryId = IsLiveSite ? 0 : VersionHistoryID;
                attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName), null, versionHistoryId));
            }
            else
            {
                attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attachmentGuid, 0));
            }
            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

            // Ensure correct URL for non-temporary attachments
            if ((OriginalNodeSiteName != SiteContext.CurrentSiteName) && !isTemp)
            {
                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 iconTag = UIHelper.GetFileIcon(Page, attachmentExt, tooltip: attachmentName);

            if (isImage)
            {
                return("<a href=\"#\" onclick=\"javascript: window.open('" + attachmentUrl + "'); return false;\" class=\"cms-icon-link\"><span " + tooltip + ">" + iconTag + attachmentName + "</span></a>");
            }
            else
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "disposition", "attachment");

                // NOTE: OnClick here is needed to avoid loader to show because even for download links, the pageUnload event is fired
                return(String.Format("<a href=\"{0}\" onclick=\"javascript: {5}\" class=\"cms-icon-link\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, attachmentGuid, tooltip, iconTag, attachmentName, ScriptHelper.GetDisableProgressScript()));
            }
        }

        case "attachmentsize":
        {
            long size = ValidationHelper.GetLong(parameter, 0);
            return(DataHelper.GetSizeString(size));
        }
        }

        return(parameter);
    }
    protected object gridFile_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        GridViewRow gvr;
        DataRowView drv;
        string      fileGuid;

        switch (sourceName?.ToLowerInvariant())
        {
        case "edit":
            if (sender is CMSAccessibleButton)
            {
                gvr = (GridViewRow)parameter;
                drv = (DataRowView)gvr.DataItem;

                fileGuid = ValidationHelper.GetString(drv["MetaFileGUID"], "");
                string fileExtension = ValidationHelper.GetString(drv["MetaFileExtension"], "");

                // Initialize properties
                CMSGridActionButton btnImageEditor = (CMSGridActionButton)sender;
                btnImageEditor.Visible = true;

                // Display button only if 'Modify' is allowed
                if (AllowModify)
                {
                    string query = $"?refresh=1&metafileguid={fileGuid}&clientid={ClientID}";
                    query = URLHelper.AddUrlParameter(query, "hash", QueryHelper.GetHash(query));

                    // Display button only if metafile is in supported image format
                    if (ImageHelper.IsSupportedByImageEditor(fileExtension))
                    {
                        // Initialize button with script
                        btnImageEditor.OnClientClick = $"OpenImageEditor({ScriptHelper.GetString(query)}); return false;";
                    }
                    // Non-image metafile
                    else
                    {
                        // Initialize button with script
                        btnImageEditor.OnClientClick = $"OpenEditor({ScriptHelper.GetString(query)}); return false;";
                    }
                }
                else
                {
                    btnImageEditor.Enabled = false;
                }
            }
            break;

        case "delete":
            if (sender is CMSGridActionButton)
            {
                CMSGridActionButton btnDelete = (CMSGridActionButton)sender;
                btnDelete.Enabled = AllowModify;
            }
            break;

        case "name":
            drv = (DataRowView)parameter;

            string fileName = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileName"), string.Empty);
            fileGuid = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileGUID"), string.Empty);
            string fileExt = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileExtension"), string.Empty);

            bool   isImage = ImageHelper.IsImage(fileExt);
            string fileUrl = $"{URLHelper.GetAbsoluteUrl("~/CMSPages/GetMetaFile.aspx")}?fileguid={fileGuid}&chset={Guid.NewGuid()}";

            // Tooltip
            string title = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileTitle"), string.Empty);

            string description = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileDescription"), string.Empty);
            int    imageWidth  = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageWidth"), 0);
            int    imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageHeight"), 0);
            string tooltip     = UIHelper.GetTooltipAttributes(fileUrl, imageWidth, imageHeight, title, fileName, fileExt, description, null, 300);

            // Icon
            string iconTag = UIHelper.GetFileIcon(Page, fileExt, tooltip: fileName);
            if (isImage)
            {
                return($"<a href=\"#\" onclick=\"javascript: window.open('{fileUrl}'); return false;\" class=\"cms-icon-link\"><span id=\"{fileGuid}\" {tooltip}>{iconTag}{fileName}</span></a>");
            }
            else
            {
                return($"<a href=\"{fileUrl}\" class=\"cms-icon-link\"><span id=\"{fileGuid}\" {tooltip}>{iconTag}{fileName}</span></a>");
            }

        case "size":
            return(DataHelper.GetSizeString(ValidationHelper.GetLong(parameter, 0)));

        case "update":
        {
            drv = (DataRowView)parameter;

            Panel pnlBlock = new Panel
            {
                ID = "pnlBlock"
            };

            string siteName = null;

            if (SiteID > 0)
            {
                SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteID);
                if (si != null)
                {
                    siteName = si.SiteName;
                }
            }
            else
            {
                siteName = SiteContext.CurrentSiteName;
            }

            // Add update control
            // Dynamically load uploader control
            var dfuElem = Page.LoadUserControl("~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploader.ascx") as DirectFileUploader;
            if (dfuElem != null)
            {
                dfuElem.ID                 = "dfuElem" + ObjectID;
                dfuElem.SourceType         = MediaSourceEnum.MetaFile;
                dfuElem.ControlGroup       = "Uploader_" + ObjectID;
                dfuElem.DisplayInline      = true;
                dfuElem.ForceLoad          = true;
                dfuElem.MetaFileID         = ValidationHelper.GetInteger(drv["MetaFileID"], 0);
                dfuElem.ObjectID           = ObjectID;
                dfuElem.ObjectType         = ObjectType;
                dfuElem.Category           = Category;
                dfuElem.ParentElemID       = ClientID;
                dfuElem.ShowIconMode       = true;
                dfuElem.InsertMode         = false;
                dfuElem.ParentElemID       = ClientID;
                dfuElem.IncludeNewItemInfo = true;
                dfuElem.SiteID             = SiteID;
                dfuElem.IsLiveSite         = IsLiveSite;

                // Setting of the direct single mode
                dfuElem.UploadMode        = MultifileUploaderModeEnum.DirectSingle;
                dfuElem.Width             = 16;
                dfuElem.Height            = 16;
                dfuElem.MaxNumberToUpload = 1;

                if (AllowedExtensions != null)
                {
                    dfuElem.AllowedExtensions = AllowedExtensions;
                }

                pnlBlock.Controls.Add(dfuElem);
            }

            // Setup external edit
            ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.MetaFile, siteName, new DataRowContainer(drv), IsLiveSite);

            return(pnlBlock);
        }
        }
        return(parameter);
    }
    /// <summary>
    /// UniGrid external data bound.
    /// </summary>
    protected object gridAttachments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView drv;

        switch (sourceName.ToLowerCSafe())
        {
        case "clone":
            CMSGridActionButton imgClone = sender as CMSGridActionButton;
            if (imgClone != null)
            {
                if (IsLiveSite)
                {
                    // Hide cloning on live site
                    imgClone.Visible = false;
                    return(imgClone);
                }

                string objectType = VersionHistoryID > 0 ? AttachmentHistoryInfo.OBJECT_TYPE : AttachmentInfo.OBJECT_TYPE;

                int id = ValidationHelper.GetInteger(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentID"], 0);

                imgClone.PreRender    += imgClone_PreRender;
                imgClone.OnClientClick = "modalDialog('" + URLHelper.ResolveUrl("~/CMSModules/Objects/Dialogs/CloneObjectDialog.aspx?objectType=" + objectType + "&objectId=" + id) + "', 'CloneObject', 750, 470); return false;";
            }
            break;

        case "update":
        {
            Panel pnlBlock = new Panel
            {
                ID = "pnlBlock"
            };

            pnlBlock.Style.Add("margin", "0 auto");
            pnlBlock.PreRender += (senderObject, args) => pnlBlock.Width = mUpdateIconPanelWidth;

            // Add update control
            // Dynamically load uploader control
            var dfuElem = Page.LoadUserControl("~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploader.ascx") as DirectFileUploader;

            drv = parameter as DataRowView;

            // Set uploader's properties
            if (dfuElem != null)
            {
                dfuElem.SourceType = MediaSourceEnum.DocumentAttachments;
                dfuElem.ID         = "dfuElem" + DocumentID;
                dfuElem.IsLiveSite = IsLiveSite;
                dfuElem.EnableSilverlightUploader = false;
                dfuElem.ControlGroup      = "update";
                dfuElem.AttachmentGUID    = GetAttachmentGuid(drv);
                dfuElem.DisplayInline     = true;
                dfuElem.UploadMode        = MultifileUploaderModeEnum.DirectSingle;
                dfuElem.MaxNumberToUpload = 1;
                dfuElem.PreRender        += dfuElem_PreRender;
                pnlBlock.Controls.Add(dfuElem);
            }

            // Check if external edit allowed by the form
            bool allowExt = (Form == null) || Form.AllowExternalEditing;

            if (allowExt && (FormGUID == Guid.Empty))
            {
                var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.Attachment, SiteName, new DataRowContainer(drv), IsLiveSite, Node);
                if (ctrl != null)
                {
                    ctrl.Enabled = Enabled;
                    ctrl.ID      = "extEdit" + DocumentID;

                    // Ensure form identification
                    if ((Form != null) && (Form.Parent != null))
                    {
                        ctrl.FormID = Form.Parent.ClientID;
                    }
                    ctrl.SiteName = SiteName;

                    ctrl.PreRender += extEdit_PreRender;

                    if (FieldInfo != null)
                    {
                        ctrl.AttachmentFieldName = FieldInfo.Name;
                    }

                    // Adjust styles
                    bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());

                    pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");
                    mUpdateIconPanelWidth = 32;
                }
            }

            return(pnlBlock);
        }

        case "edit":
            // Get file extension
            string extension        = ValidationHelper.GetString(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentExtension"], string.Empty).ToLowerCSafe();
            Guid   guid             = ValidationHelper.GetGuid(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentGUID"], Guid.Empty);
            CMSGridActionButton img = sender as CMSGridActionButton;
            if (img != null)
            {
                img.ToolTip    = String.Format("{0}|{1}", extension, guid);
                img.PreRender += img_PreRender;
            }
            break;

        case "delete":
            CMSGridActionButton imgDelete = sender as CMSGridActionButton;
            if (imgDelete != null)
            {
                // Turn off validation
                imgDelete.CausesValidation = false;
                imgDelete.PreRender       += imgDelete_PreRender;
            }
            break;

        case "moveup":
            CMSGridActionButton imgUp = sender as CMSGridActionButton;
            if (imgUp != null)
            {
                // Turn off validation
                imgUp.CausesValidation = false;
                imgUp.PreRender       += imgUp_PreRender;
            }
            break;

        case "movedown":
            CMSGridActionButton imgDown = sender as CMSGridActionButton;
            if (imgDown != null)
            {
                // Turn off validation
                imgDown.CausesValidation = false;
                imgDown.PreRender       += imgDown_PreRender;
            }
            break;

        case "attachmentname":
        {
            drv = parameter as DataRowView;

            if (drv == null)
            {
                break;
            }

            // Get attachment GUID
            Guid attachmentGuid = GetAttachmentGuid(drv);

            // Get attachment extension
            string attachmentExt = GetAttachmentExtension(drv);
            bool   isImage       = ImageHelper.IsImage(attachmentExt);

            // Get link for attachment
            string attachmentUrl;

            string attName    = ValidationHelper.GetString(drv["AttachmentName"], string.Empty);
            int    documentId = DocumentID;

            if (Node != null)
            {
                if (IsLiveSite && (documentId > 0))
                {
                    attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName)));
                }
                else
                {
                    attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName), null, VersionHistoryID));
                }
            }
            else
            {
                attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attachmentGuid, VersionHistoryID));
            }
            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

            // Ensure correct URL for non-temporary attachments
            if ((OriginalNodeSiteName != SiteContext.CurrentSiteName) && (documentId > 0))
            {
                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(DataHelper.GetDataRowViewValue(drv, "AttachmentTitle"), string.Empty);
                string description = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "AttachmentDescription"), string.Empty);
                int    imageWidth  = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "AttachmentImageWidth"), 0);
                int    imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "AttachmentImageHeight"), 0);

                tooltip = UIHelper.GetTooltipAttributes(attachmentUrl, imageWidth, imageHeight, title, attachmentName, attachmentExt, description, null, 300);
            }

            // Icon
            string imageTag = UIHelper.GetFileIcon(Page, attachmentExt);

            if (isImage)
            {
                return(String.Format("<a class=\"cms-icon-link\" href=\"#\" onclick=\"javascript: window.open('{0}'); return false;\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, attachmentGuid, tooltip, imageTag, attachmentName));
            }
            else
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "disposition", "attachment");

                // NOTE: OnClick here is needed to avoid loader to show because even for download links, the pageUnload event is fired
                return(String.Format("<a class=\"cms-icon-link\" onclick=\"javascript: {5}\" href=\"{0}\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, attachmentGuid, tooltip, imageTag, attachmentName, ScriptHelper.GetDisableProgressScript()));
            }
        }

        case "attachmentsize":
            long size = ValidationHelper.GetLong(parameter, 0);
            return(DataHelper.GetSizeString(size));
        }

        return(parameter);
    }