/// <summary>
    /// Handles external databound event of unigrid.
    /// </summary>
    protected object OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        int  userID;
        bool isUserAdministrator;

        switch (sourceName.ToLowerCSafe())
        {
        case "userenabled":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "edit":
            // Edit action
            userID = ValidationHelper.GetInteger(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserID"], 0);
            isUserAdministrator = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserIsGlobalAdministrator"], false);
            if (!CurrentUserObj.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) && isUserAdministrator && (userID != CurrentUserObj.UserID))
            {
                CMSGridActionButton button = ((CMSGridActionButton)sender);
                button.Enabled = false;
            }

            break;

        case "delete":
            // Delete action
            isUserAdministrator = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserIsGlobalAdministrator"], false);
            if (!CurrentUserObj.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) && isUserAdministrator)
            {
                CMSGridActionButton button = ((CMSGridActionButton)sender);
                button.Enabled = false;
            }
            break;

        case "roles":
            // Roles action
            userID = ValidationHelper.GetInteger(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserID"], 0);
            isUserAdministrator = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserIsGlobalAdministrator"], false);

            if (!CurrentUserObj.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) && isUserAdministrator && (userID != CurrentUserObj.UserID))
            {
                CMSGridActionButton button = ((CMSGridActionButton)sender);
                button.Enabled = false;
            }

            break;

        case "haspassword":
            // Has password action
        {
            CMSGridActionButton button = ((CMSGridActionButton)sender);

            if (!CurrentUserObj.IsGlobalAdministrator)
            {
                button.Visible = false;
            }
            else
            {
                bool isExternal  = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserIsExternal"], false);
                bool isPublic    = ValidationHelper.GetString(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserName"], string.Empty).EqualsCSafe("public", true);
                bool hasPassword = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserHasPassword"], true);

                button.OnClientClick = "return false;";
                button.Visible       = !hasPassword && !isPublic && !isExternal;
            }
        }
        break;

        case "formattedusername":
            return(HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(Convert.ToString(parameter))));

        case "#objectmenu":
            userID = ValidationHelper.GetInteger(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserID"], 0);
            isUserAdministrator = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserIsGlobalAdministrator"], false);
            if (!CurrentUserObj.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) && isUserAdministrator && (userID != CurrentUserObj.UserID))
            {
                CMSGridActionButton button = ((CMSGridActionButton)sender);
                button.Visible = false;
            }
            break;
        }
        return(parameter);
    }
Пример #2
0
    /// <summary>
    /// External data binding handler.
    /// </summary>
    protected object gridDocuments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        int currentNodeId = 0;

        sourceName = sourceName.ToLower();
        switch (sourceName)
        {
        case "published":
        {
            // Published state
            bool published = ValidationHelper.GetBoolean(parameter, true);
            if (published)
            {
                return("<span class=\"DocumentPublishedYes\">" + GetString("General.Yes") + "</span>");
            }
            else
            {
                return("<span class=\"DocumentPublishedNo\">" + GetString("General.No") + "</span>");
            }
        }

        case "versionnumber":
        {
            // Version number
            if (parameter == DBNull.Value)
            {
                parameter = "-";
            }
            parameter = HTMLHelper.HTMLEncode(parameter.ToString());

            return(parameter);
        }

        case "documentname":
        {
            // Document name
            DataRowView data          = (DataRowView)parameter;
            string      className     = ValidationHelper.GetString(data["ClassName"], string.Empty);
            string      name          = ValidationHelper.GetString(data["DocumentName"], string.Empty);
            string      culture       = ValidationHelper.GetString(data["DocumentCulture"], string.Empty);
            string      cultureString = null;

            currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0);

            int    nodeParentId     = ValidationHelper.GetInteger(data["NodeParentID"], 0);
            string preferredCulture = CMSContext.PreferredCultureCode;

            // Default culture
            if (culture.ToLower() != preferredCulture.ToLower())
            {
                cultureString = " (" + culture + ")";
            }

            string tooltip = UniGridFunctions.DocumentNameTooltip(data);

            string imageUrl = null;
            if (className.Equals("cms.file", StringComparison.InvariantCultureIgnoreCase))
            {
                string extension = ValidationHelper.GetString(data["DocumentType"], "");
                imageUrl = GetFileIconUrl(extension, "List");
            }
            // Use class icons
            else
            {
                imageUrl = ResolveUrl(GetDocumentTypeIconUrl(className));
            }

            StringBuilder sb = new StringBuilder();
            sb.Append(
                "<img src=\"", imageUrl, "\" class=\"UnigridActionButton\" /> ",
                "<a href=\"javascript: SelectItem(", currentNodeId, ", ", nodeParentId, ");\" ",
                "onmouseout=\"UnTip()\" onmouseover=\"Tip('", tooltip, "')\">",
                HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)), cultureString,
                "</a>"
                );

            // Prepare parameters
            int    workflowStepId = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(data, "DocumentWorkflowStepID"), 0);
            string stepName       = null;

            if (workflowStepId > 0)
            {
                WorkflowStepInfo stepInfo = WorkflowStepInfoProvider.GetWorkflowStepInfo(workflowStepId);
                if (stepInfo != null)
                {
                    stepName = stepInfo.StepName;
                }
            }

            // Create data container
            IDataContainer container = new DataRowContainer(data);

            // Add icons
            sb.Append(" ", UIHelper.GetDocumentMarks(Page, currentSiteName, preferredCulture, stepName, container));

            return(sb.ToString());
        }

        case "documentculture":
        {
            // Dynamically load document flags control
            DocumentFlagsControl ucDocFlags = Page.LoadControl("~/CMSAdminControls/UI/DocumentFlags.ascx") as DocumentFlagsControl;

            // Set document flags properties
            if (ucDocFlags != null)
            {
                // Get node ID
                currentNodeId = ValidationHelper.GetInteger(parameter, 0);

                ucDocFlags.ID             = "docFlags" + currentNodeId;
                ucDocFlags.SiteCultures   = SiteCultures;
                ucDocFlags.NodeID         = currentNodeId;
                ucDocFlags.StopProcessing = true;

                // Keep the control for later usage
                FlagsControls.Add(ucDocFlags);
                return(ucDocFlags);
            }
        }
        break;

        case "modifiedwhen":
        case "modifiedwhentooltip":
            // Modified when
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return("");
            }
            else
            {
                DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                if (currentUserInfo == null)
                {
                    currentUserInfo = CMSContext.CurrentUser;
                }
                if (currentSiteInfo == null)
                {
                    currentSiteInfo = CMSContext.CurrentSite;
                }

                bool displayGMT = (sourceName == "modifiedwhentooltip");
                return(TimeZoneHelper.ConvertToUserTimeZone(modifiedWhen, displayGMT, currentUserInfo, currentSiteInfo));
            }

        case "classdisplayname":
        case "classdisplaynametooltip":
            // Localize class display name
            if (!string.IsNullOrEmpty(parameter.ToString()))
            {
                return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(parameter.ToString())));
            }

            return("");
        }

        return(parameter);
    }
Пример #3
0
    /// <summary>
    /// Handles data bound event.
    /// </summary>
    protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        string      result = string.Empty;
        DataRowView data;

        switch (sourceName.ToLowerCSafe())
        {
        case "view":
        {
            CMSGridActionButton editButton = ((CMSGridActionButton)sender);
            var dataItemRow = ((DataRowView)(((GridViewRow)(parameter)).DataItem)).Row;
            var nodeID      = dataItemRow.Field <Int32>("NodeID");

            editButton.Attributes.Add("data-node-id", nodeID.ToString());
            break;
        }

        // Create link to event document
        case "documentname":
        {
            data = (DataRowView)parameter;
            string siteName     = ValidationHelper.GetString(data["SiteName"], String.Empty);
            string documentName = ValidationHelper.GetString(data["DocumentName"], String.Empty);
            string culture      = ValidationHelper.GetString(data["DocumentCulture"], String.Empty);
            int    nodeID       = ValidationHelper.GetInteger(data["NodeID"], 0);

            SiteInfo si = SiteInfoProvider.GetSiteInfo(siteName);
            if (si != null)
            {
                return("<a class=\"js-unigrid-action js-edit\" " +
                       "href=\"javascript:void(0)\" " +
                       "data-node-id=\"" + nodeID + "\" " +
                       "data-document-culture=\"" + culture + "\" >" + HTMLHelper.HTMLEncode(documentName) + "</a>");
            }
        }
            return(HTMLHelper.HTMLEncode(parameter.ToString()));

        case "eventtooltip":
            data = (DataRowView)parameter;
            return(UniGridFunctions.DocumentNameTooltip(data));

        case "eventdate":
        case "eventopenfrom":
        case "eventopento":
        case "eventdatetooltip":
        case "eventopenfromtooltip":
        case "eventopentotooltip":
            if (!String.IsNullOrEmpty(parameter.ToString()))
            {
                if (currentUserInfo == null)
                {
                    currentUserInfo = MembershipContext.AuthenticatedUser;
                }
                if (currentSiteInfo == null)
                {
                    currentSiteInfo = SiteContext.CurrentSite;
                }

                if (sourceName.EndsWithCSafe("tooltip"))
                {
                    return(mGMTTooltip ?? (mGMTTooltip = TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo)));
                }

                DateTime time = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                return(TimeZoneHelper.ConvertToUserTimeZone(time, true, currentUserInfo, currentSiteInfo));
            }
            return(result);

        case "eventenddate":
        case "eventenddatetooltip":
            data = (DataRowView)parameter;
            try
            {
                parameter = data["eventenddate"];
            }
            catch
            {
                parameter = null;
            }

            if ((parameter != null) && !String.IsNullOrEmpty(parameter.ToString()))
            {
                if (currentUserInfo == null)
                {
                    currentUserInfo = MembershipContext.AuthenticatedUser;
                }
                if (currentSiteInfo == null)
                {
                    currentSiteInfo = SiteContext.CurrentSite;
                }

                if (sourceName.EndsWithCSafe("tooltip"))
                {
                    return(mGMTTooltip ?? (mGMTTooltip = TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo)));
                }

                DateTime time = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                return(TimeZoneHelper.ConvertToUserTimeZone(time, true, currentUserInfo, currentSiteInfo));
            }
            return(result);
        }

        return(parameter);
    }
Пример #4
0
    /// <summary>
    /// External data binding handler.
    /// </summary>
    protected object gridDocuments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        int currentNodeId;

        sourceName = sourceName.ToLowerCSafe();
        switch (sourceName)
        {
        case "view":
        {
            // Dialog view item
            DataRowView         data = ((DataRowView)((GridViewRow)parameter).DataItem);
            CMSGridActionButton btn  = ((CMSGridActionButton)sender);
            // Current row is the Root document
            isRootDocument    = (ValidationHelper.GetInteger(data["NodeParentID"], 0) == 0);
            currentNodeId     = ValidationHelper.GetInteger(data["NodeID"], 0);
            isCurrentDocument = (currentNodeId == WOpenerNodeID);

            string culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty);
            // Existing document culture
            if (culture.ToLowerCSafe() == CultureCode.ToLowerCSafe())
            {
                // Force redirection to the root document in case of on-site editing (to ensure that user is not redirected to default alias path document)
                string url = ResolveUrl(!isRootDocument ? DocumentURLProvider.GetPresentationUrlHandlerPath(culture, currentNodeId) : "~/");

                btn.OnClientClick = "ViewItem(" + ScriptHelper.GetString(url) + "); return false;";
            }
            // New culture version
            else
            {
                btn.OnClientClick = "wopener.NewDocumentCulture(" + currentNodeId + ", '" + CultureCode + "'); CloseDialog(); return false;";
            }
        }
        break;

        case "edit":
        {
            CMSGridActionButton btn = ((CMSGridActionButton)sender);
            if (IsEditVisible)
            {
                DataRowView data    = ((DataRowView)((GridViewRow)parameter).DataItem);
                string      culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty);
                currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0);
                int nodeParentId = ValidationHelper.GetInteger(data["NodeParentID"], 0);

                if (!RequiresDialog || (culture.ToLowerCSafe() == CultureCode.ToLowerCSafe()))
                {
                    // Go to the selected document or create a new culture version when not used in a dialog
                    btn.OnClientClick = "EditItem(" + currentNodeId + ", " + nodeParentId + "); return false;";
                }
                else
                {
                    // New culture version in a dialog
                    btn.OnClientClick = "wopener.NewDocumentCulture(" + currentNodeId + ", '" + CultureCode + "'); CloseDialog(); return false;";
                }
            }
            else
            {
                btn.Visible = false;
            }
        }
        break;

        case "delete":
        {
            // Delete button
            CMSGridActionButton btn = ((CMSGridActionButton)sender);

            // Hide the delete button for the root document
            btn.Visible = !isRootDocument;
        }
        break;

        case "contextmenu":
        {
            // Dialog context menu item
            CMSGridActionButton btn = ((CMSGridActionButton)sender);

            // Hide the context menu for the root document
            btn.Visible = !isRootDocument && !ShowAllLevels;
        }
        break;

        case "versionnumber":
        {
            // Version number
            if (parameter == DBNull.Value)
            {
                parameter = "-";
            }
            parameter = HTMLHelper.HTMLEncode(parameter.ToString());

            return(parameter);
        }

        case "documentname":
        {
            // Document name
            DataRowView data             = (DataRowView)parameter;
            string      className        = ValidationHelper.GetString(data["ClassName"], string.Empty);
            string      classDisplayName = ValidationHelper.GetString(data["classdisplayname"], null);
            string      name             = ValidationHelper.GetString(data["DocumentName"], string.Empty);
            string      culture          = ValidationHelper.GetString(data["DocumentCulture"], string.Empty);
            string      cultureString    = null;

            currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0);
            int nodeParentId = ValidationHelper.GetInteger(data["NodeParentID"], 0);

            if (isRootDocument)
            {
                // User site name for the root document
                name = SiteContext.CurrentSiteName;
            }

            // Default culture
            if (culture.ToLowerCSafe() != CultureCode.ToLowerCSafe())
            {
                cultureString = " (" + culture + ")";
            }

            StringBuilder sb = new StringBuilder();

            var    isFile    = className.EqualsCSafe(SystemDocumentTypes.File, true);
            string extension = isFile ? ValidationHelper.GetString(data["DocumentType"], String.Empty) : String.Empty;

            if (ShowDocumentTypeIcon)
            {
                // Prepare tooltip for document type icon
                string iconTooltip = "";
                if (ShowDocumentTypeIconTooltip && (classDisplayName != null))
                {
                    string safeClassName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(classDisplayName));
                    iconTooltip = string.Format("onmouseout=\"UnTip()\" onmouseover=\"Tip('{0}')\"", HTMLHelper.EncodeForHtmlAttribute(safeClassName));
                }

                if (isFile)
                {
                    sb.Append(UIHelper.GetFileIcon(Page, extension, additionalAttributes: iconTooltip));
                }
                // Use class icons
                else
                {
                    var dataClass = DataClassInfoProvider.GetDataClassInfo(className);
                    if (dataClass != null)
                    {
                        var iconClass = (string)dataClass.GetValue("ClassIconClass");
                        sb.Append(UIHelper.GetDocumentTypeIcon(Page, className, iconClass, additionalAttributes: iconTooltip));
                    }
                }
            }

            string safeName = HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50));
            if (DocumentNameAsLink && !isRootDocument)
            {
                string tooltip = UniGridFunctions.DocumentNameTooltip(data);

                string selectFunction = SelectItemJSFunction + "(" + currentNodeId + ", " + nodeParentId + ");";
                sb.Append("<a href=\"javascript: ", selectFunction, "\"");

                // Ensure onclick action on mobile devices. This is necessary due to Tip/UnTip functions. They block default click behavior on mobile devices.
                if (DeviceContext.CurrentDevice.IsMobile)
                {
                    sb.Append(" ontouchend=\"", selectFunction, "\"");
                }

                sb.Append(" onmouseout=\"UnTip()\" onmouseover=\"Tip('", HTMLHelper.EncodeForHtmlAttribute(tooltip), "')\">", safeName, cultureString, "</a>");
            }
            else
            {
                sb.Append(safeName, cultureString);
            }

            // Show document marks only if method is not called from grid export and document marks are allowed
            if ((sender != null) && ShowDocumentMarks)
            {
                // Prepare parameters
                int workflowStepId            = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(data, "DocumentWorkflowStepID"), 0);
                WorkflowStepTypeEnum stepType = WorkflowStepTypeEnum.Undefined;

                if (workflowStepId > 0)
                {
                    WorkflowStepInfo stepInfo = WorkflowStepInfoProvider.GetWorkflowStepInfo(workflowStepId);
                    if (stepInfo != null)
                    {
                        stepType = stepInfo.StepType;
                    }
                }

                // Create data container
                IDataContainer container = new DataRowContainer(data);

                // Add icons and use current culture of processed node because of 'Not translated document' icon
                sb.Append(" ", DocumentUIHelper.GetDocumentMarks(Page, currentSiteName, ValidationHelper.GetString(container.GetValue("DocumentCulture"), string.Empty), stepType, container));
            }

            return(sb.ToString());
        }

        case "documentculture":
        {
            DocumentFlagsControl ucDocFlags = null;

            if (OnDocumentFlagsCreating != null)
            {
                // Raise event for obtaining custom DocumentFlagControl
                object result = OnDocumentFlagsCreating(this, sourceName, parameter);
                ucDocFlags = result as DocumentFlagsControl;

                // Check if something other than DocumentFlagControl was returned
                if ((ucDocFlags == null) && (result != null))
                {
                    return(result);
                }
            }

            // Dynamically load document flags control when not created
            if (ucDocFlags == null)
            {
                ucDocFlags = LoadUserControl("~/CMSAdminControls/UI/DocumentFlags.ascx") as DocumentFlagsControl;
            }

            // Set document flags properties
            if (ucDocFlags != null)
            {
                DataRowView data = (DataRowView)parameter;

                // Get node ID
                currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0);

                if (!string.IsNullOrEmpty(SelectLanguageJSFunction))
                {
                    ucDocFlags.SelectJSFunction = SelectLanguageJSFunction;
                }

                ucDocFlags.ID             = "docFlags" + currentNodeId;
                ucDocFlags.SiteCultures   = SiteCultures;
                ucDocFlags.NodeID         = currentNodeId;
                ucDocFlags.StopProcessing = true;

                // Keep the control for later usage
                FlagsControls.Add(ucDocFlags);
                return(ucDocFlags);
            }
        }
        break;

        case "modifiedwhen":
        case "modifiedwhentooltip":
            // Modified when
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return(string.Empty);
            }

            DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
            currentUserInfo = currentUserInfo ?? MembershipContext.AuthenticatedUser;
            currentSiteInfo = currentSiteInfo ?? SiteContext.CurrentSite;

            return(sourceName.EqualsCSafe("modifiedwhen", StringComparison.InvariantCultureIgnoreCase)
                    ? TimeZoneHelper.ConvertToUserTimeZone(modifiedWhen, true, currentUserInfo, currentSiteInfo)
                    : TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo));

        default:
            if (OnExternalAdditionalDataBound != null)
            {
                return(OnExternalAdditionalDataBound(sender, sourceName, parameter));
            }

            break;
        }

        return(parameter);
    }
Пример #5
0
    /// <summary>
    /// Unigrid external data bound handler.
    /// </summary>
    protected object uniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerInvariant())
        {
        case "yesno":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "select":
        {
            var ti = iObjectType.TypeInfo;

            DataRowView drv = (DataRowView)parameter;

            // Get item ID
            string itemID  = drv[returnColumnName].ToString();
            string hashKey = itemID;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && HasSiteIdColumn(ti) && (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) == 0))
            {
                itemID = "." + itemID;
            }

            // Store hash codes for grid items
            if (!hashItems.ContainsKey(hashKey))
            {
                hashItems.Add(hashKey, ValidationHelper.GetHashString(itemID));
            }

            // Add checkbox for multiple selection
            switch (selectionMode)
            {
            case SelectionModeEnum.Multiple:
            case SelectionModeEnum.MultipleTextBox:
            case SelectionModeEnum.MultipleButton:
            {
                var itemWithSeparators = string.Format("{0}{1}{0}", valuesSeparator, itemID);

                string checkBox = string.Format("<span class=\"checkbox\"><input id=\"chk{0}\" type=\"checkbox\" onchange=\"UpdateCheckboxAllElement();\" onclick=\"ProcessItem(this,'{1}',false,true);\" class=\"chckbox\" ", itemID, hashItems[hashKey]);
                if (hidItem.Value.IndexOf(itemWithSeparators, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    checkBox += "checked=\"checked\" ";
                }
                else
                {
                    allRowsChecked = false;
                }

                if (disabledItems.Contains(itemWithSeparators))
                {
                    checkBox += "disabled=\"disabled\" ";
                }

                checkBox += string.Format("/><label for=\"chk{0}\">&nbsp;</label></span>", itemID);

                return(checkBox);
            }
            }
        }
        break;

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

            // Get item ID
            string itemID  = drv[returnColumnName].ToString();
            string hashKey = itemID;

            // Get item name
            string itemName;

            // Special formatted user name
            if (displayNameFormat == UniSelector.USER_DISPLAY_FORMAT)
            {
                string userName = DataHelper.GetStringValue(drv.Row, "UserName");
                string fullName = DataHelper.GetStringValue(drv.Row, "FullName");

                itemName = Functions.GetFormattedUserName(userName, fullName, IsLiveSite);
            }
            else if (displayNameFormat == null)
            {
                itemName = drv[iObjectType.DisplayNameColumn].ToString();
            }
            else
            {
                MacroResolver resolver = MacroResolver.GetInstance();
                foreach (DataColumn item in drv.Row.Table.Columns)
                {
                    resolver.SetNamedSourceData(item.ColumnName, drv.Row[item.ColumnName]);
                }
                itemName = resolver.ResolveMacros(displayNameFormat);
            }

            if (RemoveMultipleCommas)
            {
                itemName = TextHelper.RemoveMultipleCommas(itemName);
            }

            // Add the prefixes
            itemName = ItemPrefix + itemName;
            itemID   = ItemPrefix + itemID;

            var ti = iObjectType.TypeInfo;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && HasSiteIdColumn(ti) && (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) == 0))
            {
                itemID = "." + itemID;
            }

            if (String.IsNullOrEmpty(itemName))
            {
                itemName = emptyReplacement;
            }

            if (AddGlobalObjectSuffix && HasSiteIdColumn(ti))
            {
                itemName += (DataHelper.GetIntValue(drv.Row, ti.SiteIDColumn) > 0 ? string.Empty : " " + GlobalObjectSuffix);
            }

            // Link action
            string onclick  = null;
            bool   disabled = disabledItems.Contains(";" + itemID + ";");
            if (!disabled)
            {
                string safeItemID = GetSafe(itemID);
                string itemHash   = ValidationHelper.GetHashString(itemID);
                switch (selectionMode)
                {
                case SelectionModeEnum.Multiple:
                case SelectionModeEnum.MultipleTextBox:
                case SelectionModeEnum.MultipleButton:
                    onclick = string.Format("ProcessItem(document.getElementById('chk{0}'),'{1}',true,true); return false;", ScriptHelper.GetString(itemID).Trim('\''), hashItems[hashKey]);
                    break;

                case SelectionModeEnum.SingleButton:
                    onclick = string.Format("SelectItems({0},'{1}'); return false;", safeItemID, itemHash);
                    break;

                case SelectionModeEnum.SingleTextBox:
                    if (allowEditTextBox)
                    {
                        if (!mHasDependingFields)
                        {
                            onclick = string.Format("SelectItems({0},{0},{1},{2},{3},'{4}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                        }
                        else
                        {
                            onclick = string.Format("SelectItemsReload({0},{0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                        }
                    }
                    else
                    {
                        if (!mHasDependingFields)
                        {
                            onclick = string.Format("SelectItems({0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                        }
                        else
                        {
                            onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                        }
                    }
                    break;

                default:
                    onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                    break;
                }

                onclick = "onclick=\"" + onclick + "\" ";
            }

            if (LocalizeItems)
            {
                itemName = ResHelper.LocalizeString(itemName);
            }

            return("<div " + (!disabled ? "class=\"SelectableItem\" " : null) + onclick + ">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(itemName, 100)) + "</div>");
        }
        }

        return(null);
    }
    protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView drv = null;

        switch (sourceName)
        {
        case "reject":
            if (sender is ImageButton)
            {
                // Get action button
                ImageButton rejectBtn = (ImageButton)sender;
                // Get full row view
                drv = UniGridFunctions.GetDataRowView((DataControlFieldCell)rejectBtn.Parent);
                // Add custom reject action
                rejectBtn.Attributes["onclick"] = "return FM_Reject_" + ClientID + "('" + drv["FriendID"] + "',null,'" + RejectDialogUrl + "');";
                return(rejectBtn);
            }
            else
            {
                return(string.Empty);
            }

        case "approve":
            if (sender is ImageButton)
            {
                // Get action button
                ImageButton approveBtn = (ImageButton)sender;
                // Get full row view
                drv = UniGridFunctions.GetDataRowView((DataControlFieldCell)approveBtn.Parent);
                // Add custom reject action
                approveBtn.Attributes["onclick"] = "return FM_Approve_" + ClientID + "('" + drv["FriendID"] + "',null,'" + ApproveDialogUrl + "');";
                return(approveBtn);
            }
            else
            {
                return(string.Empty);
            }

        case "friendrequestedwhen":
            if (currentUserInfo == null)
            {
                currentUserInfo = CMSContext.CurrentUser;
            }
            if (currentSiteInfo == null)
            {
                currentSiteInfo = CMSContext.CurrentSite;
            }
            DateTime currentDateTime = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
            if (IsLiveSite)
            {
                return(CMSContext.ConvertDateTime(currentDateTime, this));
            }
            else
            {
                return(TimeZoneHelper.GetCurrentTimeZoneDateTimeString(currentDateTime, currentUserInfo, currentSiteInfo, out usedTimeZone));
            }

        case "formattedusername":
            return(HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(Convert.ToString(parameter), IsLiveSite)));
        }
        return(parameter);
    }
Пример #7
0
    /// <summary>
    /// Loads the index information.
    /// </summary>
    public void LoadData()
    {
        if (SearchIndex == null)
        {
            return;
        }

        var isInAction = (SearchIndex.IndexFilesStatus == IndexStatusEnum.REBUILDING || SearchIndex.IndexFilesStatus == IndexStatusEnum.OPTIMIZING);
        var isNotReady = (!isInAction && SearchIndex.IndexFilesStatus != IndexStatusEnum.READY);

        // Items count
        lblItemCount.Text = ValidationHelper.GetString(SearchIndex.NumberOfIndexedItems, "0");

        // File size
        lblFileSize.Text = DataHelper.GetSizeString(SearchIndex.IndexFileSize);

        // Status
        string statusName = GetString("srch.status." + SearchIndex.IndexFilesStatus);

        // Show preloader image and link to thread log in status when in action
        if (isInAction)
        {
            var statusText = "";
            if (SearchTaskInfoProvider.IndexerThreadGuid != Guid.Empty)
            {
                string url = URLHelper.ResolveUrl("~/CMSModules/System/Debug/System_ViewLog.aspx");
                url = URLHelper.UpdateParameterInUrl(url, "threadGuid", SearchTaskInfoProvider.IndexerThreadGuid.ToString());
                if (WebFarmHelper.WebFarmEnabled)
                {
                    url = URLHelper.UpdateParameterInUrl(url, "serverName", WebFarmHelper.ServerName);
                }
                statusText = "<a href=\"javascript:void(0)\" onclick=\"modalDialog('" + url + "', 'ThreadProgress', '1000', '700');\" >" + statusName + "</a>";
            }

            ltlStatus.Text    = ScriptHelper.GetLoaderInlineHtml(Page, statusText, "form-control-text");
            ltlStatus.Visible = true;
            lblStatus.Visible = false;
        }
        else
        {
            lblStatus.Text = statusName;
        }

        // Show colored status name
        if (isNotReady)
        {
            lblStatus.Text = "<span class=\"StatusDisabled\">" + statusName + "</span>";
        }
        else if (SearchIndex.IndexFilesStatus == IndexStatusEnum.READY)
        {
            lblStatus.Text = "<span class=\"StatusEnabled\">" + statusName + "</span>";
        }

        // Is optimized
        lblIsOptimized.Text = UniGridFunctions.ColoredSpanYesNo(SearchIndex.IsOptimized());

        // Last update
        lblLastUpdate.Text = SearchIndex.IndexFilesLastUpdate.ToString();

        // Last rebuild
        lblLastRebuild.Text = GetString("general.notavailable");

        if (SearchIndex.IndexLastRebuildTime != DateTimeHelper.ZERO_TIME)
        {
            lblLastRebuild.Text = ValidationHelper.GetString(SearchIndex.IndexLastRebuildTime, "");
        }
    }
Пример #8
0
    /// <summary>
    /// External data binding handler.
    /// </summary>
    protected object gridDocuments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView data = null;

        switch (sourceName.ToLower())
        {
        case "documentname":
        {
            data = (DataRowView)parameter;

            string name                = ValidationHelper.GetString(data["NodeAliasPath"], "");
            string siteName            = ValidationHelper.GetString(data["SiteName"], "");
            int    currentNodeId       = ValidationHelper.GetInteger(data["NodeID"], 0);
            int    currentNodeParentId = ValidationHelper.GetInteger(data["NodeParentID"], 0);

            string result = null;
            if (currentSiteName == siteName.ToLower())
            {
                result = "<a href=\"javascript: SelectItem(" + currentNodeId + ", " + currentNodeParentId + ");\">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)) + "</a>";
            }
            else
            {
                result = "<span>" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)) + "</span>";
            }

            bool isLink = (data["NodeLinkedNodeID"] != DBNull.Value);
            if (isLink)
            {
                result += UIHelper.GetDocumentMarkImage(this, DocumentMarkEnum.Link);
            }

            return(result);
        }

        case "documentnametooltip":
            data = (DataRowView)parameter;
            return(UniGridFunctions.DocumentNameTooltip(data));

        case "type":
        {
            data = (DataRowView)parameter;

            int currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0);
            int linkedNodeId  = ValidationHelper.GetInteger(data["NodeLinkedNodeID"], 0);
            if (linkedNodeId == 0)
            {
                return(GetString("LinkedDocs.Original"));
            }
            else if (currentNodeId == nodeId)
            {
                return(GetString("LinkedDocs.Current"));
            }
            else
            {
                return(string.Empty);
            }
        }

        case "sitename":
        {
            string   siteName = (string)parameter;
            SiteInfo si       = SiteInfoProvider.GetSiteInfo(siteName);
            if (si != null)
            {
                return(si.DisplayName);
            }
            else
            {
                return(parameter);
            }
        }

        case "deleteaction":
        {
            GridViewRow container     = (GridViewRow)parameter;
            int         currentNodeId = ValidationHelper.GetInteger(((DataRowView)container.DataItem)["NodeID"], 0);

            bool       current = (nodeId == currentNodeId);
            const bool parent  = false;

            ((Control)sender).Visible             = ((((DataRowView)container.DataItem)["NodeLinkedNodeID"] != DBNull.Value) && !current && !parent);
            ((ImageButton)sender).CommandArgument = currentNodeId.ToString();
            break;
        }
        }
        return(parameter);
    }
Пример #9
0
    protected object gridLanguages_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        TranslationStatusEnum status;
        DataRowView           drv;

        sourceName = sourceName.ToLowerCSafe();

        if (currentUserInfo == null)
        {
            currentUserInfo = MembershipContext.AuthenticatedUser;
        }
        if (currentSiteInfo == null)
        {
            currentSiteInfo = SiteContext.CurrentSite;
        }

        switch (sourceName)
        {
        case "translate":
        case "action":
            CMSGridActionButton img = sender as CMSGridActionButton;
            if (img != null)
            {
                if ((sourceName == "translate") &&
                    (!CMS.TranslationServices.TranslationServiceHelper.AnyServiceAvailable(CurrentSiteName) ||
                     !CMS.TranslationServices.TranslationServiceHelper.IsTranslationAllowed(CurrentSiteName)))
                {
                    img.Visible = false;
                    return(img);
                }

                GridViewRow gvr = parameter as GridViewRow;
                if (gvr != null)
                {
                    // Get datarowview
                    drv = gvr.DataItem as DataRowView;

                    if ((drv != null) && (drv.Row["TranslationStatus"] != DBNull.Value))
                    {
                        // Get translation status
                        status = (TranslationStatusEnum)drv.Row["TranslationStatus"];
                    }
                    else
                    {
                        status = TranslationStatusEnum.NotAvailable;
                    }

                    string culture = (drv != null) ? ValidationHelper.GetString(drv.Row["DocumentCulture"], string.Empty) : string.Empty;

                    // Set appropriate icon
                    if (sourceName == "action")
                    {
                        switch (status)
                        {
                        case TranslationStatusEnum.NotAvailable:
                            img.IconCssClass = "icon-plus";
                            img.IconStyle    = GridIconStyle.Allow;
                            img.ToolTip      = GetString("transman.createnewculture");
                            break;

                        default:
                            img.IconCssClass = "icon-edit";
                            img.IconStyle    = GridIconStyle.Allow;
                            img.ToolTip      = GetString("transman.editculture");
                            break;
                        }

                        // Register redirect script
                        if (RequiresDialog)
                        {
                            if ((sourceName == "action") && (status == TranslationStatusEnum.NotAvailable))
                            {
                                // New culture version
                                img.OnClientClick = "parent.parent.parent.NewDocumentCulture(" + NodeID + ",'" + culture + "');";
                            }
                            else
                            {
                                // Existing culture version
                                ScriptHelper.RegisterWOpenerScript(Page);
                                var url = ResolveUrl(DocumentURLProvider.GetUrl(Node));
                                url = URLHelper.AppendQuery(url, "lang=" + culture);
                                img.OnClientClick = "window.refreshPageOnClose = true; window.reloadPageUrl = " + ScriptHelper.GetString(url) + "; if (wopener.RefreshWOpener) { wopener.RefreshWOpener(window); } CloseDialog();";
                            }
                        }
                        else
                        {
                            img.OnClientClick = "RedirectItem(" + NodeID + ", '" + culture + "');";
                        }

                        img.ID = "imgAction";
                    }
                    else
                    {
                        // Add parameters identifier and hash, encode query string
                        if (LicenseHelper.CheckFeature(RequestContext.CurrentDomain, FeatureEnum.TranslationServices))
                        {
                            string returnUrl = AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Translations/Pages/TranslateDocuments.aspx") + "?targetculture=" + culture + "&dialog=1&nodeid=" + NodeID;
                            returnUrl = URLHelper.AddParameterToUrl(returnUrl, "hash", QueryHelper.GetHash(URLHelper.GetQuery(returnUrl)));

                            img.ToolTip       = GetString("transman.translate");
                            img.OnClientClick = "modalDialog('" + returnUrl + "', 'TranslateDocument', 988, 634); ";
                        }
                        else
                        {
                            img.Visible = false;
                        }
                        break;
                    }
                }
            }
            return(img);

        case "translationstatus":
            if (parameter == DBNull.Value)
            {
                status = TranslationStatusEnum.NotAvailable;
            }
            else
            {
                status = (TranslationStatusEnum)parameter;
            }
            string statusName = GetString("transman." + status);
            string statusHtml = "<span class=\"" + status + "\">" + statusName + "</span>";
            return(statusHtml);

        case "documentculturedisplayname":
            drv = (DataRowView)parameter;
            // Add icon
            return(UniGridFunctions.DocumentCultureFlag(drv, Page));

        case "documentmodifiedwhen":
        case "documentmodifiedwhentooltip":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return("-");
            }

            if (sourceName.EqualsCSafe("documentmodifiedwhen", StringComparison.InvariantCultureIgnoreCase))
            {
                DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                return(TimeZoneHelper.ConvertToUserTimeZone(modifiedWhen, true, currentUserInfo, currentSiteInfo));
            }

            return(TimeZoneHelper.GetUTCLongStringOffset(CurrentUser, currentSiteInfo));

        case "documentlastversionnumber":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return("-");
            }
            break;

        case "documentname":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                parameter = "-";
            }
            return(HTMLHelper.HTMLEncode(parameter.ToString()));
        }

        return(parameter);
    }
Пример #10
0
    protected object gridLanguages_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        TranslationStatusEnum status = TranslationStatusEnum.NotAvailable;
        DataRowView           drv    = null;

        sourceName = sourceName.ToLowerCSafe();

        if (currentUserInfo == null)
        {
            currentUserInfo = CMSContext.CurrentUser;
        }
        if (currentSiteInfo == null)
        {
            currentSiteInfo = CMSContext.CurrentSite;
        }

        switch (sourceName)
        {
        case "translate":
        case "action":
            ImageButton img = sender as CMSImageButton;
            if (img != null)
            {
                if ((sourceName == "translate") &&
                    (!CMS.TranslationServices.TranslationServiceHelper.AnyServiceAvailable(CurrentSiteName) ||
                     !CMS.TranslationServices.TranslationServiceHelper.IsTranslationAllowed(CurrentSiteName)))
                {
                    img.Visible = false;
                    return(img);
                }

                GridViewRow gvr = parameter as GridViewRow;
                if (gvr != null)
                {
                    // Get datarowview
                    drv = gvr.DataItem as DataRowView;

                    if ((drv != null) && (drv.Row["TranslationStatus"] != DBNull.Value))
                    {
                        // Get translation status
                        status = (TranslationStatusEnum)drv.Row["TranslationStatus"];
                    }
                    else
                    {
                        status = TranslationStatusEnum.NotAvailable;
                    }

                    string culture = (drv != null) ? ValidationHelper.GetString(drv.Row["DocumentCulture"], string.Empty) : string.Empty;

                    // Set appropriate icon
                    if (sourceName == "action")
                    {
                        switch (status)
                        {
                        case TranslationStatusEnum.NotAvailable:
                            img.ImageUrl = GetImageUrl("CMSModules/CMS_Content/Properties/addculture.png");
                            img.ToolTip  = GetString("transman.createnewculture");
                            break;

                        default:
                            img.ImageUrl = GetImageUrl("CMSModules/CMS_Content/Properties/editculture.png");
                            img.ToolTip  = GetString("transman.editculture");
                            break;
                        }

                        // Register redirect script
                        if (RequiresDialog)
                        {
                            if ((sourceName == "action") && (status == TranslationStatusEnum.NotAvailable))
                            {
                                // New culture version
                                img.OnClientClick = "parent.parent.parent.NewDocumentCulture(" + NodeID + ",'" + culture + "');";
                            }
                            else
                            {
                                // Existing culture version
                                ScriptHelper.RegisterWOpenerScript(Page);
                                string url = ResolveUrl(CMSContext.GetUrl(Node.NodeAliasPath, Node.DocumentUrlPath, currentSiteInfo.SiteName));
                                url = URLHelper.AppendQuery(url, "lang=" + culture);
                                img.OnClientClick = "window.refreshPageOnClose = true; window.reloadPageUrl = " + ScriptHelper.GetString(url) + "; if (wopener.RefreshWOpener) { wopener.RefreshWOpener(window); } CloseDialog();";
                            }
                        }
                        else
                        {
                            img.OnClientClick = "RedirectItem(" + NodeID + ", '" + culture + "');";
                        }

                        img.ID = "imgAction";
                    }
                    else
                    {
                        // Add parameters identifier and hash, encode query string
                        if (LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.TranslationServices))
                        {
                            string returnUrl = CMSContext.ResolveDialogUrl("~/CMSModules/Translations/Pages/TranslateDocuments.aspx") + "?targetculture=" + culture + "&modal=1&nodeid=" + NodeID;
                            returnUrl = URLHelper.AddParameterToUrl(returnUrl, "hash", QueryHelper.GetHash(URLHelper.GetQuery(returnUrl)));

                            img.ImageUrl      = GetImageUrl("CMSModules/CMS_Content/Properties/translate.png");
                            img.ToolTip       = GetString("transman.translate");
                            img.OnClientClick = "modalDialog('" + returnUrl + "', 'TranslateDocument', 550, 440); ";
                        }
                        else
                        {
                            img.Visible = false;
                        }
                        break;
                    }
                }
            }
            return(img);

        case "translationstatus":
            if (parameter == DBNull.Value)
            {
                status = TranslationStatusEnum.NotAvailable;
            }
            else
            {
                status = (TranslationStatusEnum)parameter;
            }
            string statusName = GetString("transman." + status);
            string statusHtml = "<span class=\"" + status + "\">" + statusName + "</span>";
            // .Outdated
            return(statusHtml);

        case "documentculturedisplayname":
            drv = (DataRowView)parameter;
            // Add icon
            return(UniGridFunctions.DocumentCultureFlag(drv, Page));

        case "documentmodifiedwhen":
        case "documentmodifiedwhentooltip":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return("-");
            }
            else
            {
                DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                bool     displayGMT   = (sourceName == "documentmodifiedwhentooltip");
                return(TimeZoneHelper.ConvertToUserTimeZone(modifiedWhen, displayGMT, currentUserInfo, currentSiteInfo));
            }

        case "versionnumber":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return("-");
            }
            break;

        case "documentname":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                parameter = "-";
            }
            return(HTMLHelper.HTMLEncode(parameter.ToString()));

        case "published":
            bool published = ValidationHelper.GetBoolean(parameter, false);
            if (published)
            {
                return("<span class=\"DocumentPublishedYes\">" + GetString("General.Yes") + "</span>");
            }
            else
            {
                return("<span class=\"DocumentPublishedNo\">" + GetString("General.No") + "</span>");
            }
        }
        return(parameter);
    }
Пример #11
0
    /// <summary>
    /// Unigrid external data bound handler.
    /// </summary>
    protected object uniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
        case "yesno":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "select":
        {
            DataRowView drv = (parameter as DataRowView);

            // Get item ID
            string itemID = drv[returnColumnName].ToString();

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && !String.IsNullOrEmpty(iObjectType.SiteIDColumn) && (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) == 0))
            {
                itemID = "." + itemID;
            }

            // Add checkbox for multiple selection
            switch (selectionMode)
            {
            case SelectionModeEnum.Multiple:
            case SelectionModeEnum.MultipleTextBox:
            case SelectionModeEnum.MultipleButton:
            {
                string checkBox = "<input id=\"chk" + itemID + "\" type=\"checkbox\" onclick=\"ProcessItem(this);\" class=\"chckbox\" ";
                if (hidItem.Value.IndexOfCSafe(valuesSeparator + itemID + valuesSeparator, true) >= 0)
                {
                    checkBox += "checked=\"checked\" ";
                }
                if (disabledItems.Contains(";" + itemID + ";"))
                {
                    checkBox += "disabled=\"disabled\" ";
                }
                checkBox += "/>";

                return(checkBox);
            }
            }
        }
        break;

        case "itemname":
        {
            DataRowView drv = (parameter as DataRowView);

            // Get item ID
            string itemID = drv[returnColumnName].ToString();

            // Get item name
            string itemName = "";

            // Special formatted user name
            if (displayNameFormat == UniSelector.USER_DISPLAY_FORMAT)
            {
                string userName = ValidationHelper.GetString(DataHelper.GetDataRowValue(drv.Row, "UserName"), String.Empty);
                string fullName = ValidationHelper.GetString(DataHelper.GetDataRowValue(drv.Row, "FullName"), String.Empty);

                itemName = Functions.GetFormattedUserName(userName, fullName, IsLiveSite);
            }
            else if (displayNameFormat == null)
            {
                itemName = drv[iObjectType.DisplayNameColumn].ToString();
            }
            else
            {
                itemName = th.MergeText(displayNameFormat, drv.Row);
            }

            if (RemoveMultipleCommas)
            {
                itemName = TextHelper.RemoveMultipleCommas(itemName);
            }

            // Add the prefixes
            itemName = ItemPrefix + itemName;
            itemID   = ItemPrefix + itemID;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && !String.IsNullOrEmpty(iObjectType.SiteIDColumn) && (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) == 0))
            {
                itemID = "." + itemID;
            }

            if (String.IsNullOrEmpty(itemName))
            {
                itemName = emptyReplacement;
            }

            if (AddGlobalObjectSuffix)
            {
                if ((iObjectType != null) && !string.IsNullOrEmpty(iObjectType.SiteIDColumn))
                {
                    itemName += (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) > 0 ? "" : " " + GlobalObjectSuffix);
                }
            }

            // Link action
            string onclick  = null;
            bool   disabled = disabledItems.Contains(";" + itemID + ";");
            if (!disabled)
            {
                switch (selectionMode)
                {
                case SelectionModeEnum.Multiple:
                case SelectionModeEnum.MultipleTextBox:
                case SelectionModeEnum.MultipleButton:
                    onclick = "ProcessItem(document.getElementById('chk" + ScriptHelper.GetString(itemID).Trim('\'') + "'), true); return false;";
                    break;

                case SelectionModeEnum.SingleButton:
                    onclick = "SelectItems(" + GetSafe(itemID) + "); return false;";
                    break;

                case SelectionModeEnum.SingleTextBox:
                    if (allowEditTextBox)
                    {
                        onclick = "SelectItems(" + GetSafe(itemID) + ", " + GetSafe(itemID) + ", " + ScriptHelper.GetString(hdnClientId) + ", " + ScriptHelper.GetString(txtClientId) + "); return false;";
                    }
                    else
                    {
                        onclick = "SelectItems(" + GetSafe(itemID) + ", " + GetSafe(itemName) + ", " + ScriptHelper.GetString(hdnClientId) + ", " + ScriptHelper.GetString(txtClientId) + "); return false;";
                    }
                    break;

                default:
                    onclick = "SelectItemsReload(" + GetSafe(itemID) + ", " + GetSafe(itemName) + ", " + ScriptHelper.GetString(hdnClientId) + ", " + ScriptHelper.GetString(txtClientId) + ", " + ScriptHelper.GetString(hdnDrpId) + "); return false;";
                    break;
                }

                onclick = "onclick=\"" + onclick + "\" ";
            }

            if (LocalizeItems)
            {
                itemName = ResHelper.LocalizeString(itemName);
            }

            return("<div " + (!disabled ? "class=\"SelectableItem\" " : null) + onclick + ">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(itemName, 100)) + "</div>");
        }
        }

        return(null);
    }
Пример #12
0
    /// <summary>
    ///  On external databound event.
    /// </summary>
    object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        int userID = 0;

        switch (sourceName)
        {
        // Check if user was kicked and if so inform about it
        case "formattedusername":
            DataRowView drv = (DataRowView)parameter;
            if (drv != null)
            {
                UserInfo ui = new UserInfo(drv.Row);
                if (ui != null)
                {
                    string userName = Functions.GetFormattedUserName(ui.UserName);
                    if (UserInfoProvider.UserKicked(ui.UserID))
                    {
                        return(HTMLHelper.HTMLEncode(userName) + " <span style=\"color:#ee0000;\">" + GetString("administration.users.onlineusers.kicked") + "</span>");
                    }

                    return(HTMLHelper.HTMLEncode(userName));
                }
            }
            return("");

        // Is user enabled
        case "userenabled":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "kick":
            userID = ValidationHelper.GetInteger(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserID"], 0);
            bool userIsAdmin = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserIsGlobalAdministrator"], false);

            if (UserInfoProvider.UserKicked(userID) || userIsAdmin)
            {
                ImageButton button = ((ImageButton)sender);
                button.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/Kickdisabled.png");
                button.Enabled  = false;
            }
            else
            {
                ImageButton button = ((ImageButton)sender);
                button.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/Kick.png");
                button.Enabled  = true;
            }
            return("");

        case "undokick":
            userID = ValidationHelper.GetInteger(((DataRowView)((GridViewRow)parameter).DataItem).Row["UserID"], 0);
            if (UserInfoProvider.UserKicked(userID))
            {
                ImageButton button = ((ImageButton)sender);
                button.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/Undo.png");
                button.Enabled  = true;
            }
            else
            {
                ImageButton button = ((ImageButton)sender);
                button.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/Undodisabled.png");
                button.Enabled  = false;
            }
            return("");

        default:
            return("");
        }
    }
    /// <summary>
    /// OnPreRender event handler
    /// </summary>
    /// <param name="e"></param>
    protected override void OnPreRender(EventArgs e)
    {
        if (SearchTaskInfo != null)
        {
            GeneralizedInfo relatedObjectInfo = ProviderHelper.GetInfoById(SearchTaskInfo.SearchTaskRelatedObjectType, SearchTaskInfo.SearchTaskRelatedObjectID);
            string          relatedObjectStr  = String.Empty;

            if (relatedObjectInfo == null)
            {
                relatedObjectStr = LocalizationHelper.GetStringFormat(
                    "smartsearch.searchtaskrelatedobjectnotexist",
                    TypeHelper.GetNiceObjectTypeName(SearchTaskInfo.SearchTaskRelatedObjectType),
                    SearchTaskInfo.SearchTaskRelatedObjectID
                    );
            }
            else
            {
                relatedObjectStr = relatedObjectInfo.GetFullObjectName(false, true, false);
            }

            StringBuilder report = new StringBuilder();
            report.Append("<div class='form-horizontal'>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.tasktype"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(GetString("smartsearch.tasktype." + SearchTaskInfo.SearchTaskType.ToStringRepresentation())), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskobjecttype"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(TypeHelper.GetNiceObjectTypeName(SearchTaskInfo.SearchTaskObjectType)), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskfield"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(SearchTaskInfo.SearchTaskField), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskvalue"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(SearchTaskInfo.SearchTaskValue), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskrelatedobject"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(relatedObjectStr), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskservername"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(SearchTaskInfo.SearchTaskServerName), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskcreated"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(SearchTaskInfo.SearchTaskCreated.ToString()), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskstatus"), ":</span></div><div class='editing-form-value-cell'><span class='form-control-text'>", UniGridFunctions.ColoredSpanMsg(HTMLHelper.HTMLEncode(GetString("smartsearch.searchtaskstatusenum." + SearchTaskInfo.SearchTaskStatus.ToStringRepresentation())), SearchTaskInfo.SearchTaskStatus != SearchTaskStatusEnum.Error), "</span></div></div>");
            report.Append("<div class='form-group'><div class='editing-form-label-cell'><span class='control-label'>", GetString("smartsearch.task.taskerrormessage"), ":</strong></div><div class='editing-form-value-cell'><span class='form-control-text'>", HTMLHelper.HTMLEncode(SearchTaskInfo.SearchTaskErrorMessage), "</span></div></div>");
            report.Append("</div>");

            lblReport.Text = report.ToString();
        }
        else
        {
            lblReport.Text = GetString("srch.task.tasknotexist");
        }
    }
Пример #14
0
    /// <summary>
    /// External data binding handler.
    /// </summary>
    private object Control_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        bool running;

        switch (sourceName.ToLowerCSafe())
        {
        case "openlivesite":
        {
            // Open live site action
            DataRowView row = (DataRowView)((GridViewRow)parameter).DataItem;
            running = SiteIsRunning(row["SiteStatus"]);
            if (!running)
            {
                var button = ((CMSGridActionButton)sender);
                button.Enabled = false;
            }
        }
        break;

        case "sitestatus":
            // Colorize site status
        {
            DataRowView row = (DataRowView)parameter;
            running = SiteIsRunning(row["SiteStatus"]);
            bool offline = ValidationHelper.GetBoolean(row["SiteIsOffline"], false);

            if (running)
            {
                if (offline)
                {
                    return(UniGridFunctions.SpanMsg(ResHelper.GetString("Site_List.Offline"), "SiteStatusOffline"));
                }
                else
                {
                    return(UniGridFunctions.SpanMsg(ResHelper.GetString("Site_List.Running"), "SiteStatusRunning"));
                }
            }
            else
            {
                return(UniGridFunctions.SpanMsg(ResHelper.GetString("Site_List.Stopped"), "SiteStatusStopped"));
            }
        }

        case "culture":
            // Culture with flag
        {
            DataRowView row         = (DataRowView)parameter;
            string      siteName    = ValidationHelper.GetString(row["SiteName"], "");
            string      cultureCode = CultureHelper.GetDefaultCultureCode(siteName);
            return(UniGridFunctions.DocumentCultureFlag(cultureCode, null, Control.Page));
        }

        case "start":
        {
            // Start action
            DataRowView row = (DataRowView)((GridViewRow)parameter).DataItem;
            running = SiteIsRunning(row["SiteStatus"]);
            ((CMSGridActionButton)sender).Visible = !running;
        }
        break;

        case "stop":
        {
            // Stop action
            DataRowView row = (DataRowView)((GridViewRow)parameter).DataItem;
            running = SiteIsRunning(row["SiteStatus"]);
            ((CMSGridActionButton)sender).Visible = running;
        }
        break;
        }

        return(parameter);
    }
    protected object UniGridWorkflowScopes_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(GetString("general.selectall"));
            }
            return(docType);

        case "scopecultureid":
            int cultureId = ValidationHelper.GetInteger(parameter, 0);
            if (cultureId > 0)
            {
                return(CultureInfoProvider.GetCultureInfo(cultureId).CultureName);
            }
            else
            {
                return(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(GetString("workflowscope.children"));
            }
            else
            {
                // Only document
                if (!children)
                {
                    return(GetString("workflowscope.doc"));
                }
                // Document including children
                else
                {
                    return(GetString("workflowscope.docandchildren"));
                }
            }
        }

        default:
            return(parameter);
        }
    }
Пример #16
0
    private object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView rowView = parameter as DataRowView;

        if (rowView != null)
        {
            SKUInfo sku = new SKUInfo(rowView.Row);
            switch (sourceName.ToLowerCSafe())
            {
            case "skuname":
                string fullName = sku.SKUName;

                // For variant, add name from parent SKU
                if (sku.SKUParentSKUID != 0)
                {
                    SKUInfo parentSku = SKUInfo.Provider.Get(sku.SKUParentSKUID);
                    fullName = string.Format("{0}: {1}", parentSku.SKUName, sku.SKUName);
                }
                return(HTMLHelper.HTMLEncode(fullName));

            case "optioncategory":
                OptionCategoryInfo optionCategory = OptionCategoryInfo.Provider.Get(sku.SKUOptionCategoryID);

                // Return option category display name for product option or '-' for product
                if (optionCategory != null)
                {
                    return(HTMLHelper.HTMLEncode(optionCategory.CategoryDisplayName ?? ""));
                }
                return("-");

            case "skunumber":
                return(ResHelper.LocalizeString(sku.SKUNumber, null, true));

            case "skuprice":
                // Format price
                return(CurrencyInfoProvider.GetFormattedPrice(sku.SKUPrice, sku.SKUSiteID));

            case "skudepartmentid":
                // Transform to display name and localize
                DepartmentInfo department = DepartmentInfo.Provider.Get(sku.SKUDepartmentID);
                return((department != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(department.DepartmentDisplayName)) : "");

            case "skumanufacturerid":
                // Transform to display name and localize
                ManufacturerInfo manufacturer = ManufacturerInfo.Provider.Get(sku.SKUManufacturerID);
                return((manufacturer != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(manufacturer.ManufacturerDisplayName)) : "");

            case "skubrandid":
                // Transform to display name and localize
                BrandInfo brand = BrandInfo.Provider.Get(sku.SKUBrandID);
                return((brand != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(brand.BrandDisplayName)) : "");

            case "skucollectionid":
                // Transform to display name and localize
                CollectionInfo collection = CollectionInfo.Provider.Get(sku.SKUCollectionID);
                return((collection != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(collection.CollectionDisplayName)) : "");

            case "skutaxclassid":
                // Transform to display name and localize
                TaxClassInfo taxClass = TaxClassInfo.Provider.Get(sku.SKUTaxClassID);
                return((taxClass != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(taxClass.TaxClassDisplayName)) : "");

            case "skusupplierid":
                // Transform to display name and localize
                SupplierInfo supplier = SupplierInfoProvider.ProviderObject.Get(sku.SKUSupplierID);
                return((supplier != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(supplier.SupplierDisplayName)) : "");

            case "skupublicstatusid":
                // Transform to display name and localize
                PublicStatusInfo publicStatus = PublicStatusInfo.Provider.Get(sku.SKUPublicStatusID);
                return((publicStatus != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(publicStatus.PublicStatusDisplayName)) : "");

            case "skuinternalstatusid":
                // Transform to display name and localize
                InternalStatusInfo internalStatus = InternalStatusInfo.Provider.Get(sku.SKUInternalStatusID);
                return((internalStatus != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(internalStatus.InternalStatusDisplayName)) : "");

            case "skuavailableitems":
                int?count     = sku.SKUAvailableItems as int?;
                int?reorderAt = sku.SKUReorderAt as int?;

                // Emphasize the number when product needs to be reordered
                if (count.HasValue && ((reorderAt.HasValue && (count <= reorderAt)) || (!reorderAt.HasValue && (count <= 0))))
                {
                    // Format message informing about insufficient stock level
                    return(String.Format("<span class=\"OperationFailed\">{0}</span>", count));
                }
                return(count);

            case "itemstobereordered":
                int difference = sku.SKUReorderAt - sku.SKUAvailableItems;

                // Return difference, or '-'
                return((difference > 0) ? difference.ToString() : "-");

            case "skusiteid":
                return(UniGridFunctions.ColoredSpanYesNo(sku.SKUSiteID == 0));
            }
        }

        return(parameter);
    }
Пример #17
0
    protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView drv;

        switch (sourceName.ToLowerCSafe())
        {
        case "result":
        {
            drv = parameter as DataRowView;
            if (drv != null)
            {
                string errorMsg = ValidationHelper.GetString(drv["SynchronizationErrorMessage"], string.Empty);

                if (!string.IsNullOrEmpty(errorMsg))
                {
                    int    synchronizationId = ValidationHelper.GetInteger(drv["SynchronizationID"], 0);
                    string logUrl            = ResolveUrl("~/CMSModules/Integration/Pages/Administration/Log.aspx?synchronizationid=") + synchronizationId;
                    return(String.Format("<a target=\"_blank\" href=\"{0}\" onclick=\"modalDialog('{0}', 'tasklog', 1400, 1200); return false;\">{1}</a>", logUrl, GetString("Tasks.ResultFailed")));
                }
            }
            return(string.Empty);
        }

        case "view":
            if (sender is CMSGridActionButton)
            {
                CMSGridActionButton viewButton = sender as CMSGridActionButton;
                drv = UniGridFunctions.GetDataRowView(viewButton.Parent as DataControlFieldCell);
                int    taskId    = ValidationHelper.GetInteger(drv["TaskID"], 0);
                string detailUrl = ResolveUrl("~/CMSModules/Integration/Pages/Administration/View.aspx?taskid=") + taskId;
                viewButton.OnClientClick = "modalDialog('" + detailUrl + "', 'tasklog', 1400, 1200); return false;";
                return(viewButton);
            }
            return(parameter);

        case "run":
            if (sender is CMSGridActionButton)
            {
                CMSGridActionButton runButton = sender as CMSGridActionButton;
                drv = UniGridFunctions.GetDataRowView(runButton.Parent as DataControlFieldCell);

                int connectorId = ValidationHelper.GetInteger(drv["SynchronizationConnectorID"], 0);
                var connector   = IntegrationConnectorInfoProvider.GetIntegrationConnectorInfo(connectorId);

                bool processingDisabled = TasksAreInbound ? !IntegrationHelper.IntegrationProcessExternal : !IntegrationHelper.IntegrationProcessInternal;
                if (processingDisabled || (connector == null) || !connector.ConnectorEnabled)
                {
                    // Set appropriate tooltip
                    if (processingDisabled)
                    {
                        runButton.ToolTip = GetString("integration.processingdisabled");
                    }
                    else
                    {
                        if ((connector != null) && !connector.ConnectorEnabled)
                        {
                            runButton.ToolTip = String.Format(GetString("integration.connectordisabled"), HTMLHelper.HTMLEncode(connector.ConnectorDisplayName));
                        }
                        else
                        {
                            runButton.ToolTip = GetString("integration.connectorunavailable");
                        }
                    }

                    runButton.Enabled       = false;
                    runButton.OnClientClick = "return false;";
                    runButton.Style.Add(HtmlTextWriterStyle.Cursor, "default");
                    return(runButton);
                }
            }
            break;
        }
        return(parameter);
    }
Пример #18
0
    private object gridData_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView row = parameter as DataRowView;

        if (DocumentListingDisplayed)
        {
            switch (sourceName.ToLowerCSafe())
            {
            case "skunumber":
            case "skuavailableitems":
            case "publicstatusid":
            case "allowforsale":
            case "skusiteid":
            case "typename":
            case "skuprice":

                if (ShowSections && (row["NodeSKUID"] == DBNull.Value))
                {
                    return(NO_DATA_CELL_VALUE);
                }

                break;

            case "edititem":
                row = ((GridViewRow)parameter).DataItem as DataRowView;

                if ((row != null) && ((row["NodeSKUID"] == DBNull.Value) || showProductsInTree))
                {
                    CMSGridActionButton btn = sender as CMSGridActionButton;
                    if (btn != null)
                    {
                        int currentNodeId = ValidationHelper.GetInteger(row["NodeID"], 0);
                        int nodeParentId  = ValidationHelper.GetInteger(row["NodeParentID"], 0);

                        if (row["NodeSKUID"] == DBNull.Value)
                        {
                            btn.IconCssClass = "icon-eye";
                            btn.IconStyle    = GridIconStyle.Allow;
                            btn.ToolTip      = GetString("com.sku.viewproducts");
                        }

                        // Go to the selected document
                        btn.OnClientClick = "EditItem(" + currentNodeId + ", " + nodeParentId + "); return false;";
                    }
                }

                break;
            }
        }

        switch (sourceName.ToLowerCSafe())
        {
        case "skunumber":
            string skuNumber = ValidationHelper.GetString(row["SKUNumber"], null);
            return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(skuNumber) ?? ""));

        case "skuavailableitems":
            var sku            = new SKUInfo(row.Row);
            int availableItems = sku.SKUAvailableItems;

            // Inventory tracked by variants
            if (sku.SKUTrackInventory == TrackInventoryTypeEnum.ByVariants)
            {
                return(GetString("com.inventory.trackedbyvariants"));
            }

            // Inventory tracking disabled
            if (sku.SKUTrackInventory == TrackInventoryTypeEnum.Disabled)
            {
                return(GetString("com.inventory.nottracked"));
            }

            // Ensure correct values for unigrid export
            if (sender == null)
            {
                return(availableItems);
            }

            // Tracking by products
            InlineEditingTextBox inlineAvailableItems = new InlineEditingTextBox();
            inlineAvailableItems.Text          = availableItems.ToString();
            inlineAvailableItems.DelayedReload = DocumentListingDisplayed;
            inlineAvailableItems.EnableEncode  = false;

            inlineAvailableItems.Formatting += (s, e) =>
            {
                var reorderAt = sku.SKUReorderAt;

                // Emphasize the number when product needs to be reordered
                if (availableItems <= reorderAt)
                {
                    // Format message informing about insufficient stock level
                    string reorderMsg = string.Format(GetString("com.sku.reorderatTooltip"), reorderAt);
                    string message    = string.Format("<span class=\"alert-status-error\" onclick=\"UnTip()\" onmouseout=\"UnTip()\" onmouseover=\"Tip('{1}')\">{0}</span>", availableItems, reorderMsg);
                    inlineAvailableItems.FormattedText = message;
                }
            };

            // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data.
            // Update data only if external data bound is called for the first time.
            if (!forceReloadData)
            {
                inlineAvailableItems.Update += (s, e) =>
                {
                    var newNumberOfItems = ValidationHelper.GetInteger(inlineAvailableItems.Text, availableItems);

                    if (ValidationHelper.IsInteger(inlineAvailableItems.Text) && (-1000000000 <= newNumberOfItems) && (newNumberOfItems <= 1000000000))
                    {
                        CheckModifyPermission(sku);

                        // Ensures that grid will display inserted value
                        sku.SKUAvailableItems = newNumberOfItems;

                        // Document list is used to display products -> document has to be updated to ensure correct sku mapping
                        if (DocumentListingDisplayed)
                        {
                            int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0);

                            // Create an instance of the Tree provider and select edited document with coupled data
                            TreeProvider tree     = new TreeProvider(MembershipContext.AuthenticatedUser);
                            TreeNode     document = tree.SelectSingleDocument(documentId);

                            if (document == null)
                            {
                                return;
                            }

                            document.SetValue("SKUAvailableItems", newNumberOfItems);
                            document.Update();

                            forceReloadData = true;
                        }
                        // Stand-alone product -> only product has to be updated
                        else
                        {
                            sku.MakeComplete(true);
                            sku.Update();

                            gridData.ReloadData();
                        }
                    }
                    else
                    {
                        inlineAvailableItems.ErrorText = GetString("com.productedit.availableitemsinvalid");
                    }
                };
            }

            return(inlineAvailableItems);

        case "skuprice":

            SKUInfo product = new SKUInfo(row.Row);

            // Ensure correct values for unigrid export
            if (sender == null)
            {
                return(product.SKUPrice);
            }

            InlineEditingTextBox inlineSkuPrice = new InlineEditingTextBox();
            inlineSkuPrice.Text          = product.SKUPrice.ToString();
            inlineSkuPrice.DelayedReload = DocumentListingDisplayed;

            inlineSkuPrice.Formatting += (s, e) =>
            {
                // Format price
                inlineSkuPrice.FormattedText = CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, product.SKUSiteID);
            };

            // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data.
            // Update data only if external data bound is called for the first time.
            if (!forceReloadData)
            {
                inlineSkuPrice.Update += (s, e) =>
                {
                    CheckModifyPermission(product);

                    // Price must be a double number
                    double price = ValidationHelper.GetDouble(inlineSkuPrice.Text, -1);

                    if (ValidationHelper.IsDouble(inlineSkuPrice.Text) && (price >= 0))
                    {
                        // Ensures that grid will display inserted price
                        product.SKUPrice = price;

                        // Document list is used to display products -> document has to be updated to ensure correct sku mapping
                        if (DocumentListingDisplayed)
                        {
                            int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0);

                            // Create an instance of the Tree provider and select edited document with coupled data
                            TreeProvider tree     = new TreeProvider(MembershipContext.AuthenticatedUser);
                            TreeNode     document = tree.SelectSingleDocument(documentId);

                            if (document != null)
                            {
                                document.SetValue("SKUPrice", price);
                                document.Update();

                                forceReloadData = true;
                            }
                        }
                        // Stand-alone product -> only product has to be updated
                        else
                        {
                            product.MakeComplete(true);
                            product.Update();

                            gridData.ReloadData();
                        }
                    }
                    else
                    {
                        inlineSkuPrice.ErrorText = GetString("com.productedit.priceinvalid");
                    }
                };
            }

            return(inlineSkuPrice);

        case "publicstatusid":
            int id = ValidationHelper.GetInteger(row["SKUPublicStatusID"], 0);
            PublicStatusInfo publicStatus = PublicStatusInfoProvider.GetPublicStatusInfo(id);
            if (publicStatus != null)
            {
                // Localize and encode
                return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(publicStatus.PublicStatusDisplayName)));
            }

            return(string.Empty);

        case "allowforsale":
            // Get "on sale" flag
            return(UniGridFunctions.ColoredSpanYesNo(ValidationHelper.GetBoolean(row["SKUEnabled"], false)));

        case "typename":
            string docTypeName = ValidationHelper.GetString(row["ClassDisplayName"], null);

            // Localize class display name
            if (!string.IsNullOrEmpty(docTypeName))
            {
                return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(docTypeName)));
            }

            return(string.Empty);
        }

        return(parameter);
    }
Пример #19
0
    protected object UniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        bool inherited             = false;
        BadWordActionEnum action   = BadWordActionEnum.None;
        string            siteName = CMSContext.CurrentSiteName;

        switch (sourceName.ToLowerCSafe())
        {
        case "wordaction":
            if (!string.IsNullOrEmpty(parameter.ToString()))
            {
                action = (BadWordActionEnum)Enum.Parse(typeof(BadWordActionEnum), parameter.ToString());
            }
            else
            {
                action    = BadWordsHelper.BadWordsAction(siteName);
                inherited = true;
            }
            // Ensure displaying text labels instead of numbers
            switch (action)
            {
            case BadWordActionEnum.Remove:
                parameter = GetString("general.remove");
                break;

            case BadWordActionEnum.Replace:
                parameter = GetString("general.replace");
                break;

            case BadWordActionEnum.ReportAbuse:
                parameter = GetString("BadWords_Edit.ReportAbuse");
                break;

            case BadWordActionEnum.RequestModeration:
                parameter = GetString("BadWords_Edit.RequestModeration");
                break;

            case BadWordActionEnum.Deny:
                parameter = GetString("Security.Deny");
                break;
            }
            if (inherited)
            {
                parameter += " " + GetString("BadWords_Edit.Inherited");
            }
            break;

        case "wordreplacement":
            // Get DataRowView
            DataRowView drv = parameter as DataRowView;
            if (drv != null)
            {
                string replacement = drv.Row["WordReplacement"].ToString();
                string toReturn    = replacement;
                // Set 'inherited' only if WordReplacement is empty
                if (string.IsNullOrEmpty(replacement))
                {
                    // Get action from cell
                    string actionText = drv.Row["WordAction"].ToString();
                    // Get action enum value
                    if (string.IsNullOrEmpty(actionText))
                    {
                        action = BadWordsHelper.BadWordsAction(siteName);
                    }
                    else
                    {
                        action = (BadWordActionEnum)Convert.ToInt32(actionText);
                    }

                    // Set replacement only if action is replace
                    if (action == BadWordActionEnum.Replace)
                    {
                        // Get inherited replacement from settings
                        if (string.IsNullOrEmpty(toReturn))
                        {
                            string inheritedSetting = SettingsKeyProvider.GetStringValue(siteName + ".CMSBadWordsReplacement");
                            toReturn += inheritedSetting + " " + GetString("BadWords_Edit.Inherited");
                        }
                    }
                    else
                    {
                        toReturn = string.Empty;
                    }
                }
                return(HTMLHelper.HTMLEncode(toReturn));
            }
            return(null);

        case "global":
            bool global = ValidationHelper.GetBoolean(parameter, false);
            return(UniGridFunctions.ColoredSpanYesNo(global));
        }
        return(HTMLHelper.HTMLEncode(parameter.ToString()));
    }
    /// <summary>
    /// Grid external data bound handler.
    /// </summary>
    protected object gridFiles_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        // Get the data row view from parameter
        DataRowView drv = null;
        if (parameter is DataRowView)
        {
            drv = (DataRowView)parameter;
        }
        else if (parameter is GridViewRow)
        {
            // Get data from the grid view row
            GridViewRow gvr = (parameter as GridViewRow);
            if (gvr != null)
            {
                drv = (DataRowView)gvr.DataItem;
            }
        }

        // Get the action button
        CMSGridActionButton btn = null;
        if (sender is CMSGridActionButton)
        {
            btn = (CMSGridActionButton)sender;
        }

        switch (sourceName)
        {
            case "delete":
                {
                    // Delete action
                    int siteId = ValidationHelper.GetInteger(drv["AttachmentSiteID"], 0);
                    string siteName = GetSiteName(siteId);

                    Guid guid = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
                    string extension = ValidationHelper.GetString(drv["AttachmentExtension"], "");

                    // Check if the file is in DB
                    bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false);

                    // Check if the file is in the file system
                    bool fs = false;
                    string path = AttachmentInfoProvider.GetFilePhysicalPath(siteName, guid.ToString(), extension);
                    if (File.Exists(path))
                    {
                        fs = true;
                    }

                    // If the file is present in both file system and database, delete is allowed
                    if (fs && db)
                    {
                        // If the files are stored in file system, delete is allowed in database 
                        if (StoreInFileSystem(siteId))
                        {
                            btn.OnClientClick = btn.OnClientClick.Replace("'delete'", "'deleteindatabase'");
                            btn.ToolTip = "Delete from database";
                            return parameter;
                        }
                        // If the files are stored in database, delete is allowed in file system
                        if (StoreInDatabase(siteId))
                        {
                            btn.OnClientClick = btn.OnClientClick.Replace("'delete'", "'deleteinfilesystem'");
                            btn.ToolTip = "Delete from file system";
                            return parameter;
                        }
                    }

                    btn.Visible = false;
                }
                break;

            case "copy":
                {
                    // Delete action
                    int siteId = ValidationHelper.GetInteger(drv["AttachmentSiteID"], 0);
                    string siteName = GetSiteName(siteId);

                    Guid guid = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
                    string extension = ValidationHelper.GetString(drv["AttachmentExtension"], "");

                    // Check if the file is in DB
                    bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false);

                    // Check if the file is in the file system
                    bool fs = false;
                    string path = AttachmentInfoProvider.GetFilePhysicalPath(siteName, guid.ToString(), extension);
                    if (File.Exists(path))
                    {
                        fs = true;
                    }

                    // If the file is stored in file system and the file is not present in database, copy to database is allowed
                    if (fs && !db && StoreInDatabase(siteId) && StoreInFileSystem(siteId))
                    {
                        btn.OnClientClick = btn.OnClientClick.Replace("'copy'", "'copytodatabase'");
                        btn.ToolTip = "Copy to database";
                        //btn.ImageUrl = 
                        return parameter;
                    }
                    // If the file is stored in database and the file is not present in file system, copy to file system is allowed
                    if (db && !fs && StoreInFileSystem(siteId))
                    {
                        btn.OnClientClick = btn.OnClientClick.Replace("'copy'", "'copytofilesystem'");
                        btn.ToolTip = "Copy to file system";
                        //btn.ImageUrl = 
                        return parameter;
                    }

                    btn.Visible = false;
                }
                break;

            case "name":
                {
                    // Attachment name
                    string name = ValidationHelper.GetString(drv["AttachmentName"], "");
                    Guid guid = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
                    int siteId = ValidationHelper.GetInteger(drv["AttachmentSiteID"], 0);
                    string extension = ValidationHelper.GetString(drv["AttachmentExtension"], "");

                    // File name
                    name = Path.GetFileNameWithoutExtension(name);

                    string url = ResolveUrl("~/CMSPages/GetFile.aspx?guid=") + guid;
                    if (siteId != currentSiteId)
                    {
                        // Add the site name to the URL if not current site
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId);
                        if (si != null)
                        {
                            url += "&sitename=" + si.SiteName;
                        }
                    }

                    string tooltipSpan = name;
                    bool isImage = ImageHelper.IsImage(extension);
                    if (isImage)
                    {
                        int imageWidth = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "AttachmentImageWidth"), 0);
                        int imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "AttachmentImageHeight"), 0);

                        string tooltip = UIHelper.GetTooltipAttributes(url, imageWidth, imageHeight, null, name, extension, null, null, 300);
                        tooltipSpan = "<span id=\"" + guid + "\" " + tooltip + ">" + name + "</span>";
                    }

                    return UIHelper.GetFileIcon(Page, extension, tooltip: name) + "&nbsp;<a href=\"" + url + "\" target=\"_blank\">" + tooltipSpan + "</a>";
                }

            case "size":
                // File size
                return DataHelper.GetSizeString(ValidationHelper.GetInteger(parameter, 0));

            case "yesno":
                // Yes / No
                return UniGridFunctions.ColoredSpanYesNo(parameter);

            case "site":
                {
                    int siteId = ValidationHelper.GetInteger(parameter, 0);
                    if (siteId > 0)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId);
                        if (si != null)
                        {
                            return si.DisplayName;
                        }
                    }
                    return null;
                }

            case "storedinfilesystem":
                {
                    // Delete action
                    int siteId = ValidationHelper.GetInteger(drv["AttachmentSiteID"], 0);
                    string siteName = GetSiteName(siteId);

                    Guid guid = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
                    string extension = ValidationHelper.GetString(drv["AttachmentExtension"], "");

                    // Check if the file is in DB
                    bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false);

                    // Check if the file is in the file system
                    bool fs = false;
                    string path = AttachmentInfoProvider.GetFilePhysicalPath(siteName, guid.ToString(), extension);
                    if (File.Exists(path))
                    {
                        fs = true;
                    }

                    return UniGridFunctions.ColoredSpanYesNo(fs);
                }
        }

        return parameter;
    }
Пример #21
0
    /// <summary>
    /// Reloads info panel.
    /// </summary>
    protected void ReloadInfoPanel()
    {
        if (sii != null)
        {
            // Keep flag if is in action status
            bool isInAction = (sii.IndexStatus == IndexStatusEnum.REBUILDING || sii.IndexStatus == IndexStatusEnum.OPTIMIZING);

            // Keep flag if index is not usable
            bool isNotReady = (!isInAction && sii.IndexStatus != IndexStatusEnum.READY);

            // get status name
            string statusName = GetString("srch.status." + sii.IndexStatus.ToString());

            // Set progress if is action status
            ltrProgress.Text = String.Empty;
            if (isInAction)
            {
                ltrProgress.Text = "<img style=\"width:12px;height:12px;\" src=\"" + UIHelper.GetImageUrl(this.Page, "Design/Preloaders/preload16.gif") + "\" alt=\"" + statusName + "\" tooltip=\"" + statusName + "\"  />";
            }

            // Fill panel info with informations about index
            lblNumberOfItemsValue.Text = ValidationHelper.GetString(sii.NumberOfIndexedItems, "0");
            lblIndexFileSizeValue.Text = DataHelper.GetSizeString(sii.IndexFileSize);
            lblIndexStatusValue.Text   = statusName;

            // use coloring for status name
            if (isNotReady)
            {
                lblIndexStatusValue.Text = "<span class=\"StatusDisabled\">" + statusName + "</span>";
            }
            else if (sii.IndexStatus == IndexStatusEnum.READY)
            {
                lblIndexStatusValue.Text = "<span class=\"StatusEnabled\">" + statusName + "</span>";
            }

            lblLastRebuildTimeValue.Text = GetString("general.notavailable");
            lblLastUpdateValue.Text      = sii.IndexLastUpdate.ToString();

            if (sii.IndexLastRebuildTime != DateTimeHelper.ZERO_TIME)
            {
                lblLastRebuildTimeValue.Text = ValidationHelper.GetString(sii.IndexLastRebuildTime, "");
            }
            lblIndexIsOptimizedValue.Text = UniGridFunctions.ColoredSpanYesNo(false);

            if (sii.IndexStatus == IndexStatusEnum.READY)
            {
                IndexSearcher searcher = sii.GetSearcher();
                if (searcher != null)
                {
                    IndexReader reader = searcher.GetIndexReader();
                    if (reader != null)
                    {
                        if (reader.IsOptimized())
                        {
                            lblIndexIsOptimizedValue.Text = UniGridFunctions.ColoredSpanYesNo(true);
                        }
                    }
                }
            }
        }
    }
Пример #22
0
    /// <summary>
    /// External data binding handler.
    /// </summary>
    protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        // Prepare variables
        string      culture;
        DataRowView data;

        sourceName = sourceName.ToLowerCSafe();
        SiteInfo site;

        switch (sourceName)
        {
        // Edit button
        case EXTERNALSOURCE_EDIT:
            if (sender is CMSGridActionButton)
            {
                var editButton = (CMSGridActionButton)sender;
                data = UniGridFunctions.GetDataRowView(editButton.Parent as DataControlFieldCell);
                site = GetSiteFromRow(data);
                int nodeId = ValidationHelper.GetInteger(data[SOURCE_NODEID], 0);
                culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty);
                string type = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(data, SOURCE_TYPE), string.Empty);

                // Check permissions
                if ((site.Status != SiteStatusEnum.Running) || (!CMSPage.IsUserAuthorizedPerContent(site.SiteName) || ((ListingType == ListingTypeEnum.All) && (type == LISTINGTYPE_RECYCLEBIN))))
                {
                    editButton.Enabled = false;
                    editButton.Style.Add(HtmlTextWriterStyle.Cursor, "default");
                }
                else
                {
                    editButton.Attributes.Add("data-site-url", ResolveSiteUrl(site));
                    editButton.Attributes.Add("data-node-id", nodeId.ToString());
                    editButton.Attributes.Add("data-document-culture", culture);
                }

                editButton.OnClientClick = "return false";
                return(editButton);
            }
            return(sender);

        // Preview button
        case EXTERNALSOURCE_PREVIEW:
            if (sender is CMSGridActionButton)
            {
                var previewButton = (CMSGridActionButton)sender;
                data = UniGridFunctions.GetDataRowView(previewButton.Parent as DataControlFieldCell);
                site = GetSiteFromRow(data);
                string type = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(data, SOURCE_TYPE), string.Empty);
                if ((site.Status != SiteStatusEnum.Running) || ((ListingType == ListingTypeEnum.All) && (type == LISTINGTYPE_RECYCLEBIN)))
                {
                    previewButton.Enabled = false;
                    previewButton.Style.Add(HtmlTextWriterStyle.Cursor, "default");
                }
                else
                {
                    culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty);
                    string nodeAliasPath = ValidationHelper.GetString(data[SOURCE_NODEALIASPATH], string.Empty);

                    // Generate preview URL
                    string url = DocumentURLProvider.GetUrl(nodeAliasPath, null, site.SiteName);
                    url = URLHelper.AddParameterToUrl(url, "viewmode", "2");
                    url = URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, culture);
                    previewButton.Attributes.Add("data-preview-url", URLHelper.ResolveUrl(url));
                }

                previewButton.OnClientClick = "return false";
                return(previewButton);
            }
            return(sender);

        // Document name column
        case EXTERNALSOURCE_DOCUMENTNAME:
            data = (DataRowView)parameter;

            string name      = ValidationHelper.GetString(data[SOURCE_DOCUMENTNAME], string.Empty);
            string className = ValidationHelper.GetString(data[SOURCE_CLASSNAME], string.Empty);

            if (name == string.Empty)
            {
                name = GetString("general.root");
            }
            // Add document type icon
            string result = string.Empty;
            switch (ListingType)
            {
            case ListingTypeEnum.DocTypeDocuments:
                break;

            default:
                var dataClass = DataClassInfoProvider.GetDataClassInfo(className);

                if (dataClass != null)
                {
                    var iconClass = (string)dataClass.GetValue(SOURCE_CLASSICONCLASS);
                    result = UIHelper.GetDocumentTypeIcon(Page, className, iconClass);
                }
                break;
            }

            result += "<span>" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)) + "</span>";

            // Show document marks only if method is not called from grid export
            if ((sender != null) && (ListingType != ListingTypeEnum.All))
            {
                bool isLink = (data.Row.Table.Columns.Contains(SOURCE_NODELINKEDNODEID) && (data[SOURCE_NODELINKEDNODEID] != DBNull.Value));
                if (isLink)
                {
                    // Add link icon
                    result += DocumentHelper.GetDocumentMarkImage(Parent.Page, DocumentMarkEnum.Link);
                }
            }
            return(result);

        // Class name column
        case EXTERNALSOURCE_CLASSDISPLAYNAME:
            string displayName = ValidationHelper.GetString(parameter, string.Empty);
            if (sourceName.ToLowerCSafe() == EXTERNALSOURCE_CLASSDISPLAYNAMETOOLTIP)
            {
                displayName = TextHelper.LimitLength(displayName, 50);
            }
            if (displayName == string.Empty)
            {
                displayName = "-";
            }
            return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(displayName)));

        case EXTERNALSOURCE_DOCUMENTNAMETOOLTIP:
            data = (DataRowView)parameter;
            return(UniGridFunctions.DocumentNameTooltip(data));

        case EXTERNALSOURCE_STEPDISPLAYNAME:
            // Step display name
            int stepId = ValidationHelper.GetInteger(parameter, 0);
            if (stepId > 0)
            {
                return(new ObjectTransformation(WorkflowStepInfo.OBJECT_TYPE, stepId)
                {
                    Transformation = "{%stepdisplayname|(encode)%}"
                });
            }

            return("-");

        // Version column
        case EXTERNALSOURCE_VERSION:
            if (parameter == DBNull.Value)
            {
                parameter = "-";
            }
            parameter = HTMLHelper.HTMLEncode(parameter.ToString());
            return(parameter);

        // Site name column
        case EXTERNALSOURCE_SITENAME:
            string siteName = ValidationHelper.GetString(parameter, string.Empty);
            site = SiteInfoProvider.GetSiteInfo(siteName);
            return(HTMLHelper.HTMLEncode(site.DisplayName));

        // Document timestamp column
        case EXTERNALSOURCE_MODIFIEDWHEN:
        case EXTERNALSOURCE_MODIFIEDWHENTOOLTIP:
            if (String.IsNullOrEmpty(parameter.ToString()))
            {
                return(String.Empty);
            }

            if (currentSiteInfo == null)
            {
                currentSiteInfo = SiteContext.CurrentSite;
            }

            if (sourceName.EqualsCSafe(EXTERNALSOURCE_MODIFIEDWHEN, StringComparison.InvariantCultureIgnoreCase))
            {
                DateTime time = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                return(TimeZoneHelper.ConvertToUserTimeZone(time, true, currentUserInfo, currentSiteInfo));
            }

            return(mGMTTooltip ?? (mGMTTooltip = TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo)));
        }

        return(parameter);
    }
Пример #23
0
    protected object gridComments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
        case "commentusername":
            return(HTMLHelper.HTMLEncode(Convert.ToString(parameter)));

        case "commenttext":
            string text = Convert.ToString(parameter);
            if (text.Length > 50)
            {
                text = text.Substring(0, 50) + "...";
            }
            return(HTMLHelper.HTMLEncode(text));

        case "commentapproved":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "commentisspam":

            return(UniGridFunctions.ColoredSpanYesNoReversed(parameter));

        case "approve":
            bool approve = ValidationHelper.GetBoolean(((DataRowView)((GridViewRow)parameter).DataItem).Row["CommentApproved"], false);
            if (!approve)
            {
                CMSGridActionButton button = ((CMSGridActionButton)sender);
                button.IconCssClass = "icon-check-circle";
                button.IconStyle    = GridIconStyle.Allow;
                button.ToolTip      = GetString("general.approve");
            }
            else
            {
                CMSGridActionButton button = ((CMSGridActionButton)sender);
                button.IconCssClass = "icon-times-circle";
                button.IconStyle    = GridIconStyle.Critical;
                button.ToolTip      = GetString("general.reject");
            }
            break;

        case "edit":
            string commentId = ((DataRowView)((GridViewRow)parameter).DataItem).Row["CommentID"].ToString();

            CMSGridActionButton editButton = ((CMSGridActionButton)sender);

            // Get filter query string
            string queryCondition = ShowFilter ? filterElem.FilterQueryString : FilterQueryString;

            // If no display use postback for refresh
            string usePostback = String.Empty;
            if (!ShowFilter)
            {
                usePostback = "&usepostback=true";
            }

            editButton.OnClientClick = "modalDialog('" + ResolveUrl("~/CMSModules/Blogs/Controls/Comment_Edit.aspx") + "?commentID=" + commentId + queryCondition + usePostback + "', 'CommentEdit', 850, 480); return false;";
            break;
        }

        return(parameter);
    }
Пример #24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterDialogScript(Page);
        ScriptHelper.RegisterApplicationConstants(Page);

        // Get the object type
        string param       = ContextMenu.Parameter;
        string objectType  = null;
        bool   groupObject = false;

        if (param != null)
        {
            string[] parms = param.Split(';');
            objectType = parms[0];
            if (parms.Length == 2)
            {
                groupObject = ValidationHelper.GetBoolean(parms[1], false);
            }
        }

        // Get empty info
        GeneralizedInfo obj = null;

        if (objectType != null)
        {
            obj = ModuleManager.GetReadOnlyObject(objectType);
            // Get correct info for listings
            if (obj.TypeInfo.Inherited)
            {
                obj = ModuleManager.GetReadOnlyObject(obj.TypeInfo.OriginalObjectType);
            }
        }

        if (obj == null)
        {
            Visible = false;
            return;
        }

        var    curUser     = MembershipContext.AuthenticatedUser;
        string curSiteName = SiteContext.CurrentSiteName;

        string menuId = ContextMenu.MenuID;

        // Relationships
        if (obj.TypeInfo.HasObjectRelationships)
        {
            iRelationships.Text = ResHelper.GetString("General.Relationships");
            iRelationships.Attributes.Add("onclick", "ContextRelationships(GetContextMenuParameter('" + menuId + "'));");
        }
        else
        {
            iRelationships.Visible = false;
        }

        // Export
        if (obj.TypeInfo.ImportExportSettings.AllowSingleExport)
        {
            if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "ExportObjects", curSiteName))
            {
                iExport.Text = ResHelper.GetString("General.Export");
                iExport.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), false);");
            }
            else
            {
                iExport.Visible = false;
            }

            if (obj.GUIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
            {
                if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "BackupObjects", curSiteName))
                {
                    iBackup.Text = ResHelper.GetString("General.Backup");
                    iBackup.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), true);");
                }
                else
                {
                    iBackup.Visible = false;
                }

                if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects", curSiteName))
                {
                    iRestore.Text = ResHelper.GetString("General.Restore");
                    iRestore.Attributes.Add("onclick", "ContextRestoreObject(GetContextMenuParameter('" + menuId + "'), true);");
                }
                else
                {
                    iRestore.Visible = false;
                }
            }
            else
            {
                iBackup.Visible  = false;
                iRestore.Visible = false;
            }
        }
        else
        {
            iExport.Visible  = false;
            iBackup.Visible  = false;
            iRestore.Visible = false;
        }

        // Versioning
        if (obj.AllowRestore && UniGridFunctions.ObjectSupportsDestroy(obj) && curUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, obj.ObjectType, curSiteName))
        {
            iDestroy.Text = ResHelper.GetString("security.destroy");
            iDestroy.Attributes.Add("onclick", "ContextDestroyObject_" + ClientID + "(GetContextMenuParameter('" + menuId + "'))");
        }
        else
        {
            iDestroy.Visible = false;
        }

        // Clonning
        if (obj.AllowClone)
        {
            iClone.Text = ResHelper.GetString("general.clone");
            iClone.Attributes.Add("onclick", "ContextCloneObject" + "(GetContextMenuParameter('" + menuId + "'))");
        }
        else
        {
            iClone.Visible = false;
        }

        bool ancestor = iRelationships.Visible;

        sep1.Visible = (iClone.Visible || iDestroy.Visible) && ancestor;
        ancestor    |= (iClone.Visible || iDestroy.Visible);
        sep2.Visible = (iBackup.Visible || iRestore.Visible || iExport.Visible) && ancestor;

        Visible = iRelationships.Visible || iExport.Visible || iBackup.Visible || iDestroy.Visible || iClone.Visible;
    }
    protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName)
        {
        case "remove":
            if (sender is CMSGridActionButton)
            {
                // Get action button
                CMSGridActionButton deleteBtn = (CMSGridActionButton)sender;
                deleteBtn.Enabled = friendsManagePermission;

                return(deleteBtn);
            }
            else
            {
                return(string.Empty);
            }

        case "reject":
            if (sender is CMSGridActionButton)
            {
                // Get action button
                CMSGridActionButton rejectBtn = (CMSGridActionButton)sender;
                // Get full row view
                DataRowView drv = UniGridFunctions.GetDataRowView((DataControlFieldCell)rejectBtn.Parent);
                // Add custom reject action
                if (friendsManagePermission)
                {
                    rejectBtn.OnClientClick = "return FM_Reject_" + ClientID + "('" + drv["FriendID"] + "',null,'" + DialogUrl + "');";
                }
                else
                {
                    rejectBtn.Enabled = false;
                }

                return(rejectBtn);
            }
            else
            {
                return(string.Empty);
            }

        case "friendapprovedwhen":
            if (currentUserInfo == null)
            {
                currentUserInfo = MembershipContext.AuthenticatedUser;
            }
            if (currentSiteInfo == null)
            {
                currentSiteInfo = SiteContext.CurrentSite;
            }
            DateTime currentDateTime = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
            if (IsLiveSite)
            {
                return(TimeZoneUIMethods.ConvertDateTime(currentDateTime, this));
            }
            else
            {
                return(TimeZoneHelper.ConvertToUserTimeZone(currentDateTime, true, currentUserInfo, currentSiteInfo));
            }

        case "formattedusername":
            return(HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(Convert.ToString(parameter), IsLiveSite)));
        }
        return(parameter);
    }
Пример #26
0
    /// <summary>
    /// Handles data bound event.
    /// </summary>
    protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        string      result = string.Empty;
        DataRowView data   = null;

        switch (sourceName.ToLower())
        {
        // Create link to event document
        case "documentname":
        {
            data = (DataRowView)parameter;
            string siteName     = ValidationHelper.GetString(data["SiteName"], String.Empty);
            string documentName = ValidationHelper.GetString(data["DocumentName"], String.Empty);
            string culture      = ValidationHelper.GetString(data["DocumentCulture"], String.Empty);
            int    nodeID       = ValidationHelper.GetInteger(data["NodeID"], 0);

            SiteInfo si = SiteInfoProvider.GetSiteInfo(siteName);
            if (si != null)
            {
                // Get current app path
                string appPath = URLHelper.ApplicationPath.TrimEnd('/');
                string domain  = si.DomainName;

                // If domain contains app path donnt add it
                if (domain.Contains("/"))
                {
                    appPath = null;
                }

                string path = URLHelper.ResolveUrl("~/CMSDesk/default.aspx?section=content&action=edit&nodeid=" + nodeID + "&culture=" + culture);

                return("<a target=\"_top\" href=\'" + path + "'\" >" + HTMLHelper.HTMLEncode(documentName) + "</a>");
            }
        }
            return(HTMLHelper.HTMLEncode(parameter.ToString()));

        case "eventtooltip":
            data = (DataRowView)parameter;
            return(UniGridFunctions.DocumentNameTooltip(data));

        case "eventdate":
        case "eventopenfrom":
        case "eventopento":
        case "eventdatetooltip":
        case "eventopenfromtooltip":
        case "eventopentotooltip":
            if (!String.IsNullOrEmpty(parameter.ToString()))
            {
                if (currentUserInfo == null)
                {
                    currentUserInfo = CMSContext.CurrentUser;
                }
                if (currentSiteInfo == null)
                {
                    currentSiteInfo = CMSContext.CurrentSite;
                }

                bool     displayGMT = sourceName.EndsWith("tooltip");
                DateTime time       = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                return(TimeZoneHelper.ConvertToUserTimeZone(time, displayGMT, currentUserInfo, currentSiteInfo));
            }
            return(result);

        case "eventenddate":
        case "eventenddatetooltip":
            data = (DataRowView)parameter;
            try
            {
                parameter = data["eventenddate"];
            }
            catch
            {
                parameter = null;
            }

            if ((parameter != null) && !String.IsNullOrEmpty(parameter.ToString()))
            {
                if (currentUserInfo == null)
                {
                    currentUserInfo = CMSContext.CurrentUser;
                }
                if (currentSiteInfo == null)
                {
                    currentSiteInfo = CMSContext.CurrentSite;
                }

                bool     displayGMT = sourceName.EndsWith("tooltip");
                DateTime time       = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);
                return(TimeZoneHelper.ConvertToUserTimeZone(time, displayGMT, currentUserInfo, currentSiteInfo));
            }
            return(result);
        }

        return(parameter);
    }
    /// <summary>
    /// Grid external data bound handler.
    /// </summary>
    protected object gridFiles_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        // Get the data row view from parameter
        DataRowView drv = null;

        if (parameter is DataRowView)
        {
            drv = (DataRowView)parameter;
        }
        else if (parameter is GridViewRow)
        {
            // Get data from the grid view row
            drv = (DataRowView)((GridViewRow)parameter).DataItem;
        }

        // Get the action button
        var btn = sender as CMSGridActionButton;

        switch (sourceName)
        {
        case "delete":
        {
            // Delete action
            int    siteId   = ValidationHelper.GetInteger(drv["AttachmentSiteID"], 0);
            string siteName = SiteInfoProvider.GetSiteName(siteId);

            Guid   guid      = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
            string extension = ValidationHelper.GetString(drv["AttachmentExtension"], "");

            // Check if the file is in DB
            bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false);

            // Check if the file is in the file system
            bool   fs   = false;
            string path = AttachmentBinaryHelper.GetFilePhysicalPath(siteName, guid.ToString(), extension);
            if (File.Exists(path))
            {
                fs = true;
            }

            // If the file is present in both file system and database, delete is allowed
            if (fs && db)
            {
                var filesLocationType = GetFilesLocationType(siteId);

                // If the files are stored in file system or use both locations, delete is allowed in database
                if (filesLocationType != FilesLocationTypeEnum.Database)
                {
                    btn.OnClientClick = btn.OnClientClick.Replace("'delete'", "'deleteindatabase'");
                    btn.ToolTip       = "Delete from database";
                    return(parameter);
                }

                // Else the files are stored in database, delete is allowed in file system
                btn.OnClientClick = btn.OnClientClick.Replace("'delete'", "'deleteinfilesystem'");
                btn.ToolTip       = "Delete from file system";
                return(parameter);
            }

            btn.Visible = false;
        }
        break;

        case "copy":
        {
            // Delete action
            int    siteId   = ValidationHelper.GetInteger(drv["AttachmentSiteID"], 0);
            string siteName = SiteInfoProvider.GetSiteName(siteId);

            Guid   guid      = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
            string extension = ValidationHelper.GetString(drv["AttachmentExtension"], "");

            // Check if the file is in DB
            bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false);

            // Check if the file is in the file system
            bool   fs   = false;
            string path = AttachmentBinaryHelper.GetFilePhysicalPath(siteName, guid.ToString(), extension);
            if (File.Exists(path))
            {
                fs = true;
            }

            var filesLocationType = GetFilesLocationType(siteId);

            // If the file is stored in file system and the file is not present in database, copy to database is allowed
            if (fs && !db && (filesLocationType == FilesLocationTypeEnum.Both))
            {
                btn.OnClientClick = btn.OnClientClick.Replace("'copy'", "'copytodatabase'");
                btn.ToolTip       = "Copy to database";
                //btn.ImageUrl =
                return(parameter);
            }
            // If the file is stored in database and the file is not present in file system, copy to file system is allowed
            if (db && !fs && filesLocationType != FilesLocationTypeEnum.Database)
            {
                btn.OnClientClick = btn.OnClientClick.Replace("'copy'", "'copytofilesystem'");
                btn.ToolTip       = "Copy to file system";
                //btn.ImageUrl =
                return(parameter);
            }

            btn.Visible = false;
        }
        break;

        case "name":
            return(GetAttachmentHtml(new DataRowContainer(drv)));

        case "size":
            // File size
            return(DataHelper.GetSizeString(ValidationHelper.GetInteger(parameter, 0)));

        case "yesno":
            // Yes / No
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "site":
        {
            int siteId = ValidationHelper.GetInteger(parameter, 0);
            if (siteId > 0)
            {
                SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId);
                if (si != null)
                {
                    return(si.DisplayName);
                }
            }
            return(null);
        }

        case "storedinfilesystem":
        {
            // Delete action
            int    siteId   = ValidationHelper.GetInteger(drv["AttachmentSiteID"], 0);
            string siteName = SiteInfoProvider.GetSiteName(siteId);

            Guid   guid      = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
            string extension = ValidationHelper.GetString(drv["AttachmentExtension"], "");

            // Check if the file is in DB
            bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false);

            // Check if the file is in the file system
            bool   fs   = false;
            string path = AttachmentBinaryHelper.GetFilePhysicalPath(siteName, guid.ToString(), extension);
            if (File.Exists(path))
            {
                fs = true;
            }

            return(UniGridFunctions.ColoredSpanYesNo(fs));
        }
        }

        return(parameter);
    }
Пример #28
0
 /// <summary>
 /// Returns colored boolean value string (TRUE -> green color, FALSE - red color)
 /// </summary>
 /// <param name="val">Boolean value string</param>
 protected string GetColoredBooleanString(object val)
 {
     return(UniGridFunctions.ColoredSpanYesNo(val));
 }
    protected object gridHistory_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        sourceName = sourceName.ToLowerInvariant();
        switch (sourceName)
        {
        case "rollback":
        {
            CMSGridActionButton imgRollback = ((CMSGridActionButton)sender);
            int versionId = ValidationHelper.GetInteger(imgRollback.CommandArgument, 0);
            if (!WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve) || !CanModify || (CheckedOutByAnotherUser && !CanCheckIn) || (versionId == Node.DocumentCheckedOutVersionHistoryID))
            {
                imgRollback.Enabled = false;
            }
        }
        break;

        case "allowdestroy":
        {
            CMSGridActionButton imgDestroy = ((CMSGridActionButton)sender);
            int versionId = ValidationHelper.GetInteger(imgDestroy.CommandArgument, 0);
            if (!CanDestroy || (CheckedOutByAnotherUser && !CanCheckIn) || (versionId == Node.DocumentCheckedOutVersionHistoryID))
            {
                imgDestroy.Enabled = false;
            }
        }
        break;

        case "modifiedwhenby":
            DataRowView data         = (DataRowView)parameter;
            DateTime    modifiedwhen = ValidationHelper.GetDateTime(data["ModifiedWhen"], DateTimeHelper.ZERO_TIME);
            int         userId       = ValidationHelper.GetInteger(data["ModifiedByUserID"], 0);

            var tr = new ObjectTransformation("cms.user", userId);
            tr.EncodeOutput   = false;
            tr.Transformation = string.Format("{0} <br /> {{% Object.GetFormattedUserName()|(encode) %}}", UniGridFunctions.UserDateTimeGMT(modifiedwhen));
            return(tr);
        }

        return(parameter);
    }
Пример #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterDialogScript(Page);
        ScriptHelper.RegisterApplicationConstants(Page);

        // Get the object type
        string param           = ContextMenu.Parameter;
        string objectType      = null;
        bool   showMoveActions = false;

        if (param != null)
        {
            string[] parameters = param.Split(';');
            objectType = parameters[0];

            showMoveActions = (parameters.Length >= 3) && ValidationHelper.GetBoolean(parameters[2], false);
        }

        // Get empty info
        GeneralizedInfo emptyObject = null;
        ObjectTypeInfo  ti          = null;
        var             uiContext   = UIContextHelper.GetUIContext(this);

        if (objectType != null)
        {
            var uiContextSiteId = ValidationHelper.GetInteger(uiContext["SiteID"], 0);
            emptyObject = UniGridFunctions.GetEmptyObjectWithSiteID(objectType, uiContextSiteId);

            ti = emptyObject.TypeInfo;

            // Get correct info for listings
            if (ti.IsListingObjectTypeInfo)
            {
                emptyObject = UniGridFunctions.GetEmptyObjectWithSiteID(ti.OriginalObjectType, uiContextSiteId);
            }
        }

        if (emptyObject == null)
        {
            Visible = false;
            return;
        }

        var    curUser     = MembershipContext.AuthenticatedUser;
        string curSiteName = SiteContext.CurrentSiteName;

        string menuId = ContextMenu.MenuID;

        if (ti.OrderColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN && showMoveActions)
        {
            iMoveUp.Attributes.Add("onclick", "ContextMoveObject_" + ClientID + "('#moveup', GetContextMenuParameter('" + menuId + "'))");
            iMoveDown.Attributes.Add("onclick", "ContextMoveObject_" + ClientID + "('#movedown', GetContextMenuParameter('" + menuId + "'))");
        }
        else
        {
            iMoveUp.Visible   = false;
            iMoveDown.Visible = false;
        }

        // Export
        if (ti.ImportExportSettings.AllowSingleExport)
        {
            if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "ExportObjects", curSiteName))
            {
                iExport.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), false);");
            }
            else
            {
                iExport.Visible = false;
            }

            if (ti.GUIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
            {
                if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "BackupObjects", curSiteName))
                {
                    iBackup.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), true);");
                }
                else
                {
                    iBackup.Visible = false;
                }

                if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects", curSiteName))
                {
                    iRestore.Attributes.Add("onclick", "ContextRestoreObject(GetContextMenuParameter('" + menuId + "'), true);");
                }
                else
                {
                    iRestore.Visible = false;
                }
            }
            else
            {
                iBackup.Visible  = false;
                iRestore.Visible = false;
            }
        }
        else
        {
            iExport.Visible  = false;
            iBackup.Visible  = false;
            iRestore.Visible = false;
        }

        // Versioning
        if (ObjectVersionManager.AllowObjectRestore(emptyObject) && UniGridFunctions.ObjectSupportsDestroy(emptyObject) && curUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, emptyObject, curSiteName))
        {
            iDestroy.Attributes.Add("onclick", "ContextDestroyObject_" + ClientID + "(GetContextMenuParameter('" + menuId + "'))");
        }
        else
        {
            iDestroy.Visible = false;
        }

        // Clonning
        if ((emptyObject.AllowClone) && (curUser.IsAuthorizedPerObject(PermissionsEnum.Modify, emptyObject, curSiteName)) && (curUser.IsAuthorizedPerObject(PermissionsEnum.Create, emptyObject, curSiteName)))
        {
            iClone.Attributes.Add("onclick", "ContextCloneObject" + "(GetContextMenuParameter('" + menuId + "'))");
        }
        else
        {
            iClone.Visible = false;
        }

        bool ancestor = (iClone.Visible || iDestroy.Visible);

        sepCloneDestroy.Visible = ancestor;
        sepExport.Visible       = (iBackup.Visible || iRestore.Visible || iExport.Visible) && ancestor;
        ancestor       |= (iBackup.Visible || iRestore.Visible || iExport.Visible);
        sepMove.Visible = (iMoveUp.Visible || iMoveDown.Visible) && ancestor;

        Visible = iExport.Visible || iBackup.Visible || iDestroy.Visible || iClone.Visible || iMoveUp.Visible || iMoveDown.Visible;
    }