private static MacroExpr GetMacroExpr(string originalExpression, string processedExpression)
    {
        var macroExpr = new MacroExpr();

        try
        {
            // Handle security
            macroExpr.Expression     = MacroSecurityProcessor.RemoveMacroSecurityParams(originalExpression, out macroExpr.SignedBy);
            macroExpr.SignatureValid = MacroSecurityProcessor.CheckMacroIntegrity(originalExpression, macroExpr.SignedBy);

            // Parse rule text
            macroExpr.RuleText   = MacroRuleTree.GetRuleText(macroExpr.Expression, true, true);
            macroExpr.Expression = MacroRuleTree.GetRuleCondition(macroExpr.Expression, true);

            // Macro expression does not support anonymous signature, remove the flag
            if (processedExpression.EndsWith("@", StringComparison.Ordinal))
            {
                processedExpression = processedExpression.Substring(0, processedExpression.Length - 1);
            }

            // Check syntax
            MacroExpression.ParseExpression(processedExpression);
        }
        catch (Exception ex)
        {
            macroExpr.Error        = true;
            macroExpr.ErrorMessage = ex.Message + "\r\n\r\n" + ex.StackTrace;
        }
        return(macroExpr);
    }
    private void RenderItem(MacroExpr expression)
    {
        var row = new HtmlTableRow();

        foreach (var cell in GetRowCells(expression))
        {
            row.Controls.Add(cell);
        }

        plcRows.Controls.Add(row);
    }
Beispiel #3
0
    private IEnumerable <HtmlTableCell> GetRowCells(MacroExpr expression)
    {
        // Expression
        string exprTag = expression.RuleText ?? HTMLHelper.HTMLEncodeLineBreaks(TextHelper.LimitLength(expression.Expression, 500));

        yield return(CreateTableCellWithClass("wrap-normal", $"<span class=\"MacroExpression\" title=\"{HTMLHelper.HTMLEncode(expression.Expression)}\">{exprTag}</span>"));

        // Syntax valid
        var errorText = UniGridFunctions.ColoredSpanYesNo(!expression.Error);

        if (!String.IsNullOrEmpty(expression.ErrorMessage))
        {
            errorText = $"<span title=\"{HTMLHelper.HTMLEncode(expression.ErrorMessage)}\">{errorText}</span>";
        }

        yield return(CreateTableCellWithClass("text-center", errorText));

        // Signature valid
        yield return(new HtmlTableCell {
            InnerHtml = $"<div class=\"text-center\">{UniGridFunctions.ColoredSpanYesNo(expression.SignatureValid)}</div><div class=\"text-center\">{expression.SignedBy.ToString()}</div>"
        });

        var anyMembersIssue = expression.MembersIssues.Any();
        var membersMessage  = $"<div class=\"text-center\">{UniGridFunctions.ColoredSpanYesNo(!anyMembersIssue)}</div>";

        if (anyMembersIssue)
        {
            membersMessage = $"{membersMessage}{String.Join("<br />", expression.MembersIssues.Select(methodIssue => $"<div class=\"text-center\">{FormatMethodIssue(methodIssue)}</div>"))}";
        }

        // Members valid
        yield return(new HtmlTableCell {
            InnerHtml = membersMessage
        });

        yield return(new HtmlTableCell
        {
            Controls =
            {
                new ObjectTransformation(expression.ObjectType, expression.ObjectID)
                {
                    UseEmptyInfoForObjectLimitedByLicense = true,
                    Transformation = "{% Object.GetFullObjectName(true, true) %}"
                }
            }
        });

        // Column
        yield return(new HtmlTableCell {
            InnerText = expression.Field
        });
    }
    /// <summary>
    /// Renders the particular macro expression
    /// </summary>
    protected void RenderItem(MacroExpr expression)
    {
        var sb = new StringBuilder();

        sb.Append("<tr>");

        // Expression
        string exprTag = expression.RuleText ?? TextHelper.EnsureHTMLLineEndings(HTMLHelper.HTMLEncode(TextHelper.LimitLength(expression.Expression, 500)));

        sb.Append("<td class=\"wrap-normal\"><span class=\"MacroExpression\" title=\"", HTMLHelper.HTMLEncode(expression.Expression), "\">", exprTag, "</span></td>");

        // Syntax valid
        var errorText = UniGridFunctions.ColoredSpanYesNo(!expression.Error);

        if (!String.IsNullOrEmpty(expression.ErrorMessage))
        {
            errorText = String.Format("<span title=\"{0}\">{1}</span>", HTMLHelper.HTMLEncode(expression.ErrorMessage), errorText);
        }

        sb.Append("<td class=\"text-center\">", errorText, "</td>");

        // Signed by
        sb.Append("<td>", HTMLHelper.HTMLEncode(expression.SignedBy), "</td>");

        // Signature valid
        sb.Append("<td class=\"text-center\">", UniGridFunctions.ColoredSpanYesNo(expression.SignatureValid), "</td><td>");

        sb.Append();

        plcRows.Controls.Add(new LiteralControl(sb.ToString()));
        sb.Clear();

        // Object
        var tr = new ObjectTransformation(expression.ObjectType, expression.ObjectID)
        {
            UseEmptyInfoForObjectLimitedByLicense = true,
            Transformation = "{% Object.GetFullObjectName(true, true) %}"
        };

        plcRows.Controls.Add(tr);

        // Column
        //sb.Append(" (", expression.ObjectID, ")");
        sb.Append("</td><td>", expression.Field, "</td></tr>");

        plcRows.Controls.Add(new LiteralControl(sb.ToString()));
        sb.Clear();
    }
    private IEnumerable <HtmlTableCell> GetRowCells(MacroExpr expression)
    {
        // Expression
        string exprTag = expression.RuleText ?? HTMLHelper.HTMLEncodeLineBreaks(TextHelper.LimitLength(expression.Expression, 500));

        yield return(CreateTableCellWithClass("wrap-normal", $"<span class=\"MacroExpression\" title=\"{HTMLHelper.HTMLEncode(expression.Expression)}\">{exprTag}</span>"));

        // Syntax valid
        var errorText = UniGridFunctions.ColoredSpanYesNo(!expression.Error);

        if (!String.IsNullOrEmpty(expression.ErrorMessage))
        {
            errorText = $"<span title=\"{HTMLHelper.HTMLEncode(expression.ErrorMessage)}\">{errorText}</span>";
        }

        yield return(CreateTableCellWithClass("text-center", errorText));

        // Signed by
        yield return(new HtmlTableCell {
            InnerText = expression.SignedBy.ToString()
        });

        // Signature valid
        yield return(CreateTableCellWithClass("text-center", UniGridFunctions.ColoredSpanYesNo(expression.SignatureValid)));

        yield return(new HtmlTableCell
        {
            Controls =
            {
                new ObjectTransformation(expression.ObjectType, expression.ObjectID)
                {
                    UseEmptyInfoForObjectLimitedByLicense = true,
                    Transformation = "{% Object.GetFullObjectName(true, true) %}"
                }
            }
        });

        // Column
        yield return(new HtmlTableCell {
            InnerText = expression.Field
        });
    }
    /// <summary>
    /// Gets the macro expression from the given object
    /// </summary>
    /// <param name="expression">Expression</param>
    private static MacroExpr GetMacroExpr(string expression)
    {
        var macroExpr = new MacroExpr();

        try
        {
            // Handle security
            macroExpr.Expression     = MacroSecurityProcessor.RemoveMacroSecurityParams(expression, out macroExpr.SignedBy);
            macroExpr.SignatureValid = MacroSecurityProcessor.CheckMacroIntegrity(expression, macroExpr.SignedBy);

            // Parse rule text
            macroExpr.RuleText   = MacroRuleTree.GetRuleText(macroExpr.Expression, true, true);
            macroExpr.Expression = MacroRuleTree.GetRuleCondition(macroExpr.Expression, true);
        }
        catch (Exception ex)
        {
            macroExpr.Error        = true;
            macroExpr.ErrorMessage = ex.Message + "\r\n\r\n" + ex.StackTrace;
        }
        return(macroExpr);
    }
    /// <summary>
    /// Gets the macros from the system
    /// </summary>
    /// <param name="startIndex">Start index</param>
    /// <param name="endIndex">End index</param>
    /// <param name="maxTotalRecords">Maximum number of total records to process</param>
    /// <param name="totalRecords">Returns the total number of records found</param>
    private IEnumerable <MacroExpr> GetMacros(int startIndex, int endIndex, int maxTotalRecords, out int totalRecords)
    {
        var index = 0;

        var textToSearch       = txtTextToSearch.Text;
        var searchByText       = !String.IsNullOrEmpty(textToSearch);
        var reportProblems     = chkReportProblems.Checked;
        var skipTestingObjects = SystemContext.DevelopmentMode && chkSkipTestingObjects.Checked;
        var type = drpType.Text;

        var result = new List <MacroExpr>();

        foreach (var objectType in GetObjectTypes())
        {
            // Skip certain object types
            switch (objectType)
            {
            case ObjectVersionHistoryInfo.OBJECT_TYPE:
            case VersionHistoryInfo.OBJECT_TYPE:
            case StagingTaskInfo.OBJECT_TYPE:
            case IntegrationTaskInfo.OBJECT_TYPE:
                continue;
            }

            // Process all objects of the given type
            var infos = new ObjectQuery(objectType)
                        .TopN(maxTotalRecords)
                        .BinaryData(false);

            var typeInfo = infos.TypeInfo;

            if (skipTestingObjects)
            {
                ExcludeTestingObjects(infos);
            }

            // Search particular expression or search macros of specific type
            infos.WhereAnyColumnContains(searchByText ? textToSearch : "{" + type);

            Action <DataRow> collectMacros = dr =>
            {
                // Process all expressions
                MacroProcessor.ProcessMacros(new DataRowContainer(dr), (context, colName) =>
                {
                    // Get original macro text with hash
                    string macroType;
                    string originalExpression  = MacroProcessor.RemoveMacroBrackets(context.GetOriginalExpression(), out macroType);
                    string processedExpression = context.Expression;

                    // Decode macro from XML if needed
                    if (MacroProcessor.IsXMLColumn(colName))
                    {
                        originalExpression  = HTMLHelper.HTMLDecode(originalExpression);
                        processedExpression = HTMLHelper.HTMLDecode(processedExpression);
                    }

                    MacroExpr e = null;
                    bool add    = false;

                    if (!searchByText || (originalExpression.IndexOf(textToSearch, StringComparison.InvariantCultureIgnoreCase) >= 0))
                    {
                        // If not tracking errors, count immediately
                        if (!reportProblems)
                        {
                            // Apply paging. (endIndex is -1 when paging is off)
                            if ((endIndex < 0) || ((index >= startIndex) && (index < endIndex)))
                            {
                                e   = GetMacroExpr(originalExpression, processedExpression);
                                add = true;
                            }

                            index++;
                        }
                        else
                        {
                            e = GetMacroExpr(originalExpression, processedExpression);

                            // Filter invalid signature / syntax
                            if (!e.SignatureValid || e.Error)
                            {
                                // Apply paging. (endIndex is -1 when paging is off)
                                if ((endIndex < 0) || ((index >= startIndex) && (index < endIndex)))
                                {
                                    add = true;
                                }

                                index++;
                            }
                        }
                    }

                    if (add)
                    {
                        // Fill in the object information
                        e.ObjectType = objectType;
                        e.ObjectID   = (typeInfo.IDColumn == ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? 0 : ValidationHelper.GetInteger(dr[typeInfo.IDColumn], 0);
                        e.Field      = colName;

                        result.Add(e);
                    }

                    return(context.Expression);
                }, new List <string> {
                    type
                });

                if ((maxTotalRecords != -1) && (index >= maxTotalRecords))
                {
                    // Enough data - cancel enumeration
                    throw new ActionCancelledException();
                }
            };

            using (var scope = new CMSConnectionScope())
            {
                scope.CommandTimeout = ConnectionHelper.LongRunningCommandTimeout;

                infos.ForEachRow(collectMacros);
            }

            if (((maxTotalRecords != -1) && (index >= maxTotalRecords)) || !CMSHttpContext.Current.Response.IsClientConnected)
            {
                break;
            }
        }

        totalRecords = index;
        return(result);
    }
    /// <summary>
    /// Gets the macro expression from the given object
    /// </summary>
    /// <param name="expression">Expression</param>
    private static MacroExpr GetMacroExpr(string expression)
    {
        var macroExpr = new MacroExpr();

        try
        {
            // Handle security
            macroExpr.Expression = MacroSecurityProcessor.RemoveMacroSecurityParams(expression, out macroExpr.SignedBy);
            macroExpr.SignatureValid = MacroSecurityProcessor.CheckMacroIntegrity(expression, macroExpr.SignedBy);

            // Parse rule text
            macroExpr.RuleText = MacroRuleTree.GetRuleText(macroExpr.Expression, true, true);
            macroExpr.Expression = MacroRuleTree.GetRuleCondition(macroExpr.Expression, true);
        }
        catch (Exception ex)
        {
            macroExpr.Error = true;
            macroExpr.ErrorMessage = ex.Message + "\r\n\r\n" + ex.StackTrace;
        }
        return macroExpr;
    }
    /// <summary>
    /// Renders the particular macro expression
    /// </summary>
    protected void RenderItem(MacroExpr expression)
    {
        var sb = new StringBuilder();

        sb.Append("<tr>");

        // Expression
        string exprTag = expression.RuleText ?? TextHelper.EnsureHTMLLineEndings(HTMLHelper.HTMLEncode(TextHelper.LimitLength(expression.Expression, 500)));

        sb.Append("<td class=\"wrap-normal\"><span class=\"MacroExpression\" title=\"", HTMLHelper.HTMLEncode(expression.Expression), "\">", exprTag, "</span></td>");

        // Syntax valid
        var errorText = UniGridFunctions.ColoredSpanYesNo(!expression.Error);
        if (!String.IsNullOrEmpty(expression.ErrorMessage))
        {
            errorText = String.Format("<span title=\"{0}\">{1}</span>", HTMLHelper.HTMLEncode(expression.ErrorMessage), errorText);
        }

        sb.Append("<td class=\"text-center\">", errorText, "</td>");

        // Signed by
        sb.Append("<td>", HTMLHelper.HTMLEncode(expression.SignedBy), "</td>");

        // Signature valid
        sb.Append("<td class=\"text-center\">", UniGridFunctions.ColoredSpanYesNo(expression.SignatureValid), "</td><td>");

        sb.Append();

        plcRows.Controls.Add(new LiteralControl(sb.ToString()));
        sb.Clear();

        // Object
        var tr = new ObjectTransformation(expression.ObjectType, expression.ObjectID)
        {
            UseEmptyInfoForObjectLimitedByLicense = true,
            Transformation = "{% Object.GetFullObjectName(true, true) %}"
        };

        plcRows.Controls.Add(tr);

        // Column
        //sb.Append(" (", expression.ObjectID, ")");
        sb.Append("</td><td>", expression.Field, "</td></tr>");

        plcRows.Controls.Add(new LiteralControl(sb.ToString()));
        sb.Clear();
    }
    /// <summary>
    /// Gets the macros from the system
    /// </summary>
    /// <param name="startIndex">Start index</param>
    /// <param name="endIndex">End index</param>
    /// <param name="maxTotalRecords">Maximum number of total records to process</param>
    /// <param name="totalRecords">Returns the total number of records found</param>
    private IEnumerable <MacroExpr> GetMacros(int startIndex, int endIndex, int maxTotalRecords, ref int totalRecords)
    {
        var index = 0;
        IEnumerable <string> objectTypes = null;

        // Get object types to search
        var selectedType = ValidationHelper.GetString(selObjectType.Value, "");

        if (!String.IsNullOrEmpty(selectedType))
        {
            if (ObjectTypeManager.GetRegisteredTypeInfo(selectedType) != null)
            {
                objectTypes = new List <string> {
                    selectedType
                };
            }
        }

        if (objectTypes == null)
        {
            objectTypes = ObjectTypeManager.ObjectTypesWithMacros;
        }

        var result = new List <MacroExpr>();
        var search = txtFilter.Text;

        var invalid     = chkInvalid.Checked;
        var skipTesting = SystemContext.DevelopmentMode && chkSkipTesting.Checked;

        var type = drpType.Text;

        foreach (var objectType in objectTypes)
        {
            // Skip certain object types
            switch (objectType)
            {
            case ObjectVersionHistoryInfo.OBJECT_TYPE:
            case VersionHistoryInfo.OBJECT_TYPE:
            case StagingTaskInfo.OBJECT_TYPE:
            case IntegrationTaskInfo.OBJECT_TYPE:
                continue;
            }

            // Process all objects of the given type
            var infos = new ObjectQuery(objectType)
                        .TopN(maxTotalRecords)
                        .BinaryData(false);

            var typeInfo = infos.TypeInfo;

            if (skipTesting)
            {
                ExcludeTestingObjects(infos);
            }

            if (!String.IsNullOrEmpty(search))
            {
                // Search particular expression
                infos.WhereAnyColumnContains(search);
            }
            else
            {
                // Search just type
                infos.WhereAnyColumnContains("{" + type);
            }

            Action <DataRow> collectMacros = dr =>
            {
                var drc = new DataRowContainer(dr);

                // Process all expressions
                MacroProcessor.ProcessMacros(drc, (expression, colName) =>
                {
                    var originalExpression = expression;

                    // Decode macro from XML
                    if (MacroProcessor.IsXMLColumn(colName))
                    {
                        expression = HTMLHelper.HTMLDecode(expression);
                    }

                    MacroExpr e = null;
                    bool add    = false;

                    if (String.IsNullOrEmpty(search) || (expression.IndexOfCSafe(search, true) >= 0))
                    {
                        // If not tracking errors, count immediately
                        if (!invalid)
                        {
                            // Apply paging. Endindex is -1 when paging is off
                            if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                            {
                                e   = GetMacroExpr(expression);
                                add = true;
                            }

                            index++;
                        }
                        else
                        {
                            e = GetMacroExpr(expression);

                            // Filter invalid signature / syntax
                            var pass = !e.SignatureValid || e.Error;
                            if (pass)
                            {
                                // Apply paging. Endindex is -1 when paging is off
                                if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                                {
                                    add = true;
                                }

                                index++;
                            }
                        }
                    }

                    if (add)
                    {
                        // Fill in the object information
                        e.ObjectType = objectType;
                        e.ObjectID   = (typeInfo.IDColumn == ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? 0 : ValidationHelper.GetInteger(dr[typeInfo.IDColumn], 0);
                        e.Field      = colName;

                        result.Add(e);
                    }

                    return(originalExpression);
                },
                                             new List <string> {
                    type
                }
                                             );

                if ((maxTotalRecords != -1) && (index >= maxTotalRecords))
                {
                    // Enough data - cancel enumeration
                    throw new ActionCancelledException();
                }
            };

            using (var scope = new CMSConnectionScope())
            {
                scope.Connection.CommandTimeout = ConnectionHelper.LongRunningCommandTimeout;

                infos.ForEachRow(collectMacros);
            }

            if (((maxTotalRecords != -1) && (index >= maxTotalRecords)) || !CMSHttpContext.Current.Response.IsClientConnected)
            {
                break;
            }
        }

        totalRecords = index;
        return(result);
    }